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.
This uses the foreach
statement modifier.
Here's what happens:
@array, "\n"
) is evaluated in list context.$_
is aliased to that scalar.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.