TExcelTAD
Home › Perl › for and foreach Loops

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

perl · try it yourself
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:

perl · try it yourself
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 form
5 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:

perl · try it yourself
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:

perl · try it yourself
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 than for (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:

perl · try it yourself
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:

perl · try it yourself
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?

  1. Nothing
  2. The whole list each time
  3. Each element, via $_
  4. The index

What happens to @n after for my $x (@n) { $x = 0 }?

  1. Nothing, $x is a copy
  2. All elements become 0
  3. Only the first becomes 0
  4. It is emptied

Which loop prints 0 through 4?

  1. for my $i (0 .. 4) { print $i }
  2. for my $i (0 .. 5) { print $i }
  3. for my $i (1 .. 4) { print $i }
  4. for (0 < 5) { print }