Search code examples
for-loopperlforeach

How do inline for loops interact with print?


Here's a reprex:

use strict; 
use warnings; 
my @array = ("word1", "word2"); 
print foreach @array, "\n"; 

The effect is to print word1word2\n. How is this line of code actually parsed by the Perl interpreter?

I think I understand what print foreach @array; would do. My understanding is that this is an inline loop that is essentially equivalent to the following foreach block:

foreach @array {
    print; # i.e. print $_; 
} 

However, it's very unclear to me why appending "\n" to this gives valid code. I've tried parenthesizing the expression in different ways, but they led to errors.


Solution

  • This uses the foreach statement modifier.

    Here's what happens:

    1. The expression after the foreach (@array, "\n") is evaluated in list context.
    2. For every scalar produced,
      1. $_ is aliased to that scalar.
      2. The expression before the foreach (print) is evaluated.

    This is similar to following:

    foreach ( @array, "\n" ) {
       print;
    }
    

    However, in the statement modifier version, there's no scope created, and one can't use next, last or redo to affect the looping.