Why does the following statement work ?

T

toralf

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{$s}\t$s" '
 
J

Joost Diepenmaat

toralf said:
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{$s}\t$s" '

Because of the wrapping implied by the -n switch. See perldoc perlrun
or use B::Deparse:

$ perl -MO=Deparse -wne ' $h{$_}++; }; foreach $s (keys %h) { print \
"$h{$s}\t$s" '
BEGIN { $^W = 1; }
LINE: while (defined($_ = <ARGV>)) {
++$h{$_};
}
foreach $s (keys %h) {
print "$h{$s}\t$s";
}
-e syntax OK
 
X

xhoster

toralf said:
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{$s}\t$s" '

from perldoc perlrun:

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

LINE:
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{$s}\t$s"}}'


Xho

--
-------------------- 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.
 
T

toralf

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

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


Xho

Thx for both answers - B::Deparse I should really give a try - and the
"END" statement of @xhoster looks like what I'll use in future to
clarify such things.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top