20

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?

tchrist
  • 78,834
  • 30
  • 123
  • 180
André Laszlo
  • 15,169
  • 3
  • 63
  • 81
  • Probably for the same reason that you can use `if`, `while`, or `unless` after a statement. – Rafe Kettler Jun 08 '11 at 15:35
  • Thanks. As you can tell I'm a Perl noob but the [beginner] meta tag is removed. – André Laszlo Jun 08 '11 at 15:52
  • 3
    There is some ambiguity between the perldocs `perlfunc` `perlop` and `perlsyn`, but between the three of these you can find almost anything. N.B. `perlfunc` is searchable with the command line switch `-f` as in `perldoc -f opendir`. – Joel Berger Jun 08 '11 at 16:21

4 Answers4

20

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

Nemo
  • 70,042
  • 10
  • 116
  • 153
3

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.

Blagovest Buyukliev
  • 42,498
  • 14
  • 94
  • 130
2

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;
Eugen Konkov
  • 22,193
  • 17
  • 108
  • 158
0

It seems to me like the standard Perl for. Takes each element and executes the body (in this case is before) with $_ substituted with each element. It is just an alternate syntax for: for (@array) { statements }

Diego Sevilla
  • 28,636
  • 4
  • 59
  • 87