Why does the following statement work ?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I'm asking , b/c the 2nd "}" is not matched and the 2nd "{" too :

echo -e "A\nB\nA\n" |\
perl -wne ' $h++; }; foreach $s (keys %h) { print "$h\t$s" '


Toralf Förster
pgp finger print: 7B1A 07F4 EC82 0F90 D4C2 8936 872A E508 7DB6 9DA3

Re: Why does the following statement work ?

Quoted text here. Click to load it

from perldoc perlrun:

     -n   causes Perl to assume the following loop around your program,
          makes it iterate over filename arguments somewhat like sed -n or

                while (<>) {
                    ...             # your program goes here

And it means this quite literally.  "Your program" is not something that
gets executed as the block inside the while loop.  Is it text that gets
wrapped up in the implicit text and compiled.  So "your program" is
perfectly free to use a "}" to close the implicitly opened "while (<>) {",
but of course that means it needs to provide a unbalanced "{" to for the
implicit "}" to close.

I tend not to use this trick, and would usually write it more like:

perl -wne ' $h++; END {foreach $s(keys %h){print "$h\t$s"}}'


-------------------- http://NewsReader.Com/ --------------------
The costs of publication of this article were defrayed in part by the
payment of page charges. This article must therefore be hereby marked
advertisement in accordance with 18 U.S.C. Section 1734 solely to indicate
this fact.

Site Timeline