The foreach Control Structure
It’s handy to be able to process an entire array or list, so Perl provides a control structure to do that. The foreach
loop steps through a list of values, executing one iteration (time through the loop) for each value:
foreach $rock (qw/ bedrock slate lava /) { print "One rock is $rock.\n"; # Prints names of three rocks }
The control variable ($rock
in that example) takes on a new value from the list for each iteration. The first time through the loop, it’s "bedrock
“; the third time, it’s "lava
“.
The control variable is not a copy of the list element—it actually is the list element. That is, if you modify the control variable inside the loop, you’ll be modifying the element in the original list, as shown in the following code snippet. This is useful and supported, but it would surprise you if you weren’t expecting it.
@rocks = qw/ bedrock slate lava /; foreach $rock (@rocks) { $rock = "\t$rock"; # put a tab in front of each element of @rocks $rock .= "\n"; # put a newline on the end of each } print "The rocks are:\n", @rocks; # Each one is indented, on its own line
What is the value of $rock
after the loop has finished? It’s the same as it was before the loop started. The value of the control variable of a foreach
loop is automatically saved and restored by Perl. While the loop is running, there’s no way to access or alter that saved value. So after the loop is done, the variable has the value it had before the loop or undef
if it didn’t have a value. ...
Get Learning Perl, Fourth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.