Prepending and Appending Code
When we use switches like -n and -p, the code that we pass runs in a loop. This avoids the need to write looping code ourselves, but it also presents a problem: all the code we pass will be executed repeatedly, once for each line in the input. Sometimes that’s fine, but if we want to do something only once—for example, some initial setup code or something right at the end to summarize what we’ve worked on—then we’re out of luck. Variables we initialize will be initialized (and so reset) on every line. Anything we output will be output for every line, not just once at the start or end.
We can sidestep this issue using two language constructs Ruby provides for us generally, not just for use with one-liners: BEGIN ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access