ela

Tutorial, lesson 7 of 9

Maps

A map holds a value for each key, written as JSON writes it: {"200": "ok", "404": "not found"}. $meaning["404"] reads a key, and meaning["500"] = "server error" sets one, adding it when it is new. A map’s keys are read with brackets; the dot is for a struct’s fields.

The log holds one request a line. str.lines splits it into lines, str.fields splits a line into its words, and the third word is the status. counts starts empty and gains a key for each status it meets.

Reading a key the map lacks is an error, never an empty value, so a typo in a key stops the script at its line. The first status the loop meets, 200, has no count yet, so counts[$status] = $counts[$status] + 1 stops there: try it, and the error names the key and both ways out. has($counts, "404") asks first; map.get($counts, $status, 0) gives the value, or 0 when the key is missing.

for status, n in $counts walks the keys and their values. A map keeps its keys in the order they were added, so the statuses come out in the order the log first had them. map.keys and map.values give them as lists, for str.join and list.sum.

Inside a string, $meaning[$status] reads a key as it does outside. A key written out goes in single quotes there, "$meaning['404']", since a double quote would end the string; or the whole read goes in ${ }, as the line for the 404 does.

What it prints
200 ok: 3
403 forbidden: 2
404 not found: 1
500 server error: 1
statuses: 200, 403, 404, 500
requests: 7
a page is missing: 1 request
redirects: 0