Skip to content
Advertisement

Perl one-liner is it possible to make END block execute for each file arg given

For Perl one-liners, when using the -p or -n flags is it possible to make the END {} block execute once per file, instead of only once for the entire program?

In other words, when I write:

JavaScript

I’d like to execute the END block once for each file, instead of just once globally at the end of the program’s execution.

Currently I just use xargs for this, but wondered if Perl maybe had some alternate flag for that behavior.

JavaScript

PS – in case you’re wondering why I don’t just just grep | wc -l for this simple case, it’s because this example is simplified from my real use case, which involves both incr (++) as well as decr (–) in the tally


Answer: Based on @mpapec’s technique, plus a small tweak to also reset the $count var per file, I get this which works:

JavaScript

Advertisement

Answer

You can check eof for end of each file,

JavaScript

or

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement