2

I've seen this one-liner

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

here: How can I sum values in column based on the value in another column?

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

Community
  • 1
  • 1
sid_com
  • 24,137
  • 26
  • 96
  • 187

1 Answers1

16

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
  • 811,555
  • 193
  • 1,581
  • 1,452