Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is Perl's postfix `for` syntax documented?

Tags:

syntax

perl

I recently came across the following code snippet

$count_stuff{$_}++ for @stuff;

It's a pretty convenient way to use a hash to count occurrences of strings in an array for example. I understand how it works, but not why it works. I can not find the documentation for this way of using for.

Why does it work? And where is the documentation?

like image 671
André Laszlo Avatar asked Jun 08 '11 15:06

André Laszlo


3 Answers

It is documented in the "perlsyn" man page, under Statement Modifiers (which talks about the postfix syntax) and under Foreach Loops (which explains that "for" and "foreach" are synonyms).

like image 94
Nemo Avatar answered Oct 16 '22 23:10

Nemo


Perl has postfix variants for many of its statements. It's just that you write the keyword after the one-statement body.

You can use if, unless, etc. in the same way.

like image 25
Blagovest Buyukliev Avatar answered Oct 17 '22 00:10

Blagovest Buyukliev


According to this page it is documented here
And you should read Foreach Loops to get answer for your question.

In short, If you you understand this well:

for my $item ( @array ) { print $item }

And know syntax of for and print:

LABEL for VAR (LIST) BLOCK
print LIST

According to the doc of foreach: If VAR is omitted, $_ is set to each value.
And according to the doc of print: If LIST is omitted, prints $_

So we can reduce the example above:

for ( @array ) { print }

In the postfix form it will look like this:

print for @array;
like image 40
Eugen Konkov Avatar answered Oct 16 '22 23:10

Eugen Konkov