Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

perl

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:

perl -ne '$count++ if/.../; END {print "$ARGV: $count" if $count > 0}' mysourcedir/*.html

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.

echo mysourcedir/*.html | xargs -n1 perl -ne '$count++ if/.../; END {print "$ARGV: $count" if $count > 0}'

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:

perl -ne '$count++ if/.../; if (eof && $count > 0) {print "$ARGV: $count"; $count = 0;} ' mysourcedir/*.html
like image 943
Magnus Avatar asked Jan 11 '23 20:01

Magnus


1 Answers

You can check eof for end of each file,

perl -ne '$count++ if/.../; eof && sub{ print "$ARGV: $count" if $count > 0 }->()' mysourcedir/*.html

or

perl -ne '$count++ if/.../; eof && do{ print "$ARGV: $count" if $count > 0 }' mysourcedir/*.html
like image 55
mpapec Avatar answered Jan 25 '23 16:01

mpapec