for and foreach Loops
Perl has two kinds of for loop: the list loop (foreach), which visits each element of a list, and the C-style loop with an initialiser, a condition and a step. The keywords for and foreach are interchangeable; most Perl programmers write for for both and reserve foreach for readability.
Looping over a list
use strict;
use warnings;
my @cities = qw(Oslo Cairo Lima);
foreach my $city (@cities) {
print "Visiting $city\n";
}
for my $n (1 .. 5) {
print $n * $n, " ";
}
print "\n";Visiting Oslo
Visiting Cairo
Visiting Lima
1 4 9 16 25
The loop variable (my $city) is local to the loop. The range operator 1 .. 5 is the easy way to count.
The default variable $_
If you leave out the loop variable, Perl uses $_. Many built-ins use $_ by default, so short loops become very compact:
use strict;
use warnings;
my @words = ("apple\n", "kiwi\n", "fig\n");
for (@words) {
chomp; # chomp($_)
print length, " "; # length($_)
}
print "\n";
print "Fruit: $_\n" for @words; # postfix form5 4 3
Fruit: apple
Fruit: kiwi
Fruit: fig
Use $_ for short, obvious loops. In longer loops a named variable is much clearer.
The loop variable is an alias
Inside foreach, the loop variable is an alias for the actual element, not a copy. Changing it changes the array:
use strict;
use warnings;
my @prices = (10, 20, 30);
for my $p (@prices) {
$p *= 1.1; # modifies @prices itself
}
print "After raise: @prices\n";
my @labels = map { "item-$_" } 1 .. 3;
s/-/_/ for @labels; # substitution on each element, in place
print "@labels\n";After raise: 11 22 33
item_1 item_2 item_3
This is handy for cleaning data in place, and a source of bugs when you didn't mean to.
C-style for
The three-part loop is useful when you need unusual steps, or two counters at once:
use strict;
use warnings;
for (my $i = 10; $i > 0; $i -= 3) {
print "$i ";
}
print "\n";
my @letters = qw(a b c d e);
for (my ($lo, $hi) = (0, $#letters); $lo < $hi; $lo++, $hi--) {
@letters[$lo, $hi] = @letters[$hi, $lo]; # swap the pair
}
print "Reversed in place: @letters\n";10 7 4 1
Reversed in place: e d c b a
Tip: For simple counting,
for my $i (0 .. $#array)is more Perl-ish thanfor (my $i = 0; $i < @array; $i++), and harder to get wrong.
Looping over a hash
Loop over the sorted keys, or use each when order does not matter:
use strict;
use warnings;
my %population = (Tokyo => 37.4, Delhi => 31.0, Shanghai => 27.1);
for my $city (sort { $population{$b} <=> $population{$a} } keys %population) {
printf "%-9s %5.1f million\n", $city, $population{$city};
}Tokyo 37.4 million
Delhi 31.0 million
Shanghai 27.1 million
Index and value together
Since Perl 5.36 you can loop over several values at a time, which makes iterating index/value pairs easy:
use strict;
use warnings;
no warnings 'experimental::for_list';
my @podium = qw(Ines Omar Yuki);
for my ($i, $name) (builtin::indexed @podium) {
print "Place ", $i + 1, ": $name\n";
}
my %color = (sky => "blue", grass => "green");
for my ($thing, $c) (map { $_, $color{$_} } sort keys %color) {
print "The $thing is $c\n";
}Place 1: Ines
Place 2: Omar
Place 3: Yuki
The grass is green
The sky is blue
builtin::indexed turns a list into (0, first, 1, second, ...), and for my ($i, $name) takes two items per pass.
Test yourself
In for (@list) { print; }, what does print print?
- Nothing
- The whole list each time
- Each element, via
$_ - The index
What happens to @n after for my $x (@n) { $x = 0 }?
- Nothing,
$xis a copy - All elements become 0
- Only the first becomes 0
- It is emptied
Which loop prints 0 through 4?
for my $i (0 .. 4) { print $i }for my $i (0 .. 5) { print $i }for my $i (1 .. 4) { print $i }for (0 < 5) { print }