foreach Loops
This loop iterates over a list of values by setting the control
variable (VAR) to each successive element
of the list:
for my VAR (LIST) {
...
}If “my
VAR” is omitted, the global $_ is used. You can omit the my, but only when use strict is turned off, so don’t.
For historical reasons, the foreach keyword is a synonym for the
for keyword, so you can use
for and foreach interchangeably, whichever you
think is more readable in a given situation. We tend to prefer
for because we are lazy and
because it is more readable, especially with
the my. (Don’t worry—Perl can
easily distinguish for (@ARGV)
from for ($i=0; $i <=$#ARGV;
$i++) because the latter contains semicolons.) Here are
some examples:
$sum = 0;
for my $value (@array) { $sum += $value }
for my $count (10,9,8,7,6,5,4,3,2,1,"BOOM") { # do a countdown
say $count;
sleep(1);
}
for (reverse "BOOM", 1 .. 10) { # same thing
say;
sleep(1);
}
for my $field (split /:/, $data) { # any LIST expression
say "Field contains: '$field'";
}
for my $key (sort keys %hash) {
say "$key => $hash{$key}";
}That last one is the canonical way to print out the values of
a hash in sorted order. See the keys and sort entries in Chapter 27 for more elaborate examples.
There is no way to tell where you are in the list. You may compare adjacent elements by remembering the previous one in a variable, but sometimes you just have to break down and write a three-part loop with subscripts. That’s why we have two different loops, after all.
If LIST consists ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access