tags:

views:

189

answers:

1

Hello, I've seen this one-liner

perl -lane '$_{$F[0]}+=$F[1]}print"$_ $_{$_}"for keys%_;{' file

here: http://stackoverflow.com/questions/2311228/sum-up-different-row-values-in-a-file-using-sed-awk-perl

and I don't remember how the "{" at the end works. Could someone explain how it works?

+15  A: 

From the Perl help:

-n   assume "while (<>) { ... }" loop around program

This is purely a textual operation, so it gives this program:

while (<>) { $_{$F[0]}+=$F[1]}print"$_ $_{$_}"for keys%_;{ }

This is an abuse of the -n switch because the while loop is closed early due to the unmatched } in the original program. But the closing } that is added by the -n switch still needs to match with something, and that's why there needs to be an extra { at the end of the program, even though it doesn't do anything.

In other words, the only reason the last { is there is to not give a syntax error.

Mark Byers
Might be nice to mention -MO=Deparse
ysth
We show several examples in _Effective Perl Programming, 2nd Edition_ that use this trick. :)
brian d foy
A better way to accomplish this (in my opinion) would be to use an `END { }` block.
Chris Lutz