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

后端 未结 4 1783
执念已碎
执念已碎 2021-02-18 16:38

I recently came across the following code snippet

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

It\'s a pretty convenient way to use a hash to count occurrenc

相关标签:
4条回答
  • 2021-02-18 17:09

    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.

    0 讨论(0)
  • 2021-02-18 17:12

    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 }

    0 讨论(0)
  • 2021-02-18 17:19

    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;
    
    0 讨论(0)
  • 2021-02-18 17:25

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

    0 讨论(0)
提交回复
热议问题