foreach and the default variable

foreach over a list

foreach visits every element of a list in order. In Perl the words for and foreach are interchangeable; write foreach when you mean a list walk, and for when you mean the three-part counter loop from lesson 15.

my @langs = qw(perl ruby python); foreach my $lang (@langs) { print "$lang\n"; }

perl demo.pl

perl
ruby
python

Any list works on the right: an array, a range, the result of a function, or a literal list in parentheses. The loop variable is a fresh lexical declared in the loop header.

The default variable

Leave the loop variable out and Perl fills the default variable $_. Many built-ins read $_ when given no argument, so short loops lose almost all their punctuation.

foreach (qw(alpha beta)) { print uc, "\n"; # ALPHA, then BETA } foreach (1..3) { print "$_ " } # 1 2 3 print "\n";

perl demo.pl

ALPHA
BETA
1 2 3

The default variable is also what pattern matches use: if (/error/) tests the current element. That is the idiom behind most Perl one-liners, which lesson 40 takes apart.

It is an alias

The loop variable is not a copy: it is an alias to the element. Assigning to it changes the array itself, which is either a neat trick or a nasty surprise depending on whether you expected it.

my @nums = (1, 2, 3); $_ *= 10 for @nums; print "@nums\n"; # 10 20 30

perl demo.pl

10 20 30

Iterating a literal list behaves differently: for (1..3) { $_ *= 10 } changes a temporary, and the numbers are gone when the loop ends. The alias only bites when the list is real storage.

Name the element

Once a loop body grows past a few lines, name the variable. The reader no longer has to remember what $_ holds, and nested loops stop fighting over it.

my @files = qw(a.log b.log); for my $file (@files) { $file =~ s/\.log$/.txt/; print "$file\n"; # a.txt, then b.txt }

perl demo.pl

a.txt
b.txt

The substitution also changes @files, because the named variable is an alias too. Copy the value first if the original list must stay untouched.

Next: Subroutines

Article author: Arthur Isaev

Banner image