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 3.7.
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 7.6 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.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is the difference between
forandforeachin Perl?Answer
Nothing: the two words are interchangeable, and the choice is a matter of what you mean
Both spell the same loop; the course writes
foreachfor a list walk andforfor the three-part counter loop. -
Which variable does a loop without a named variable fill?
Answer
$_$_is the default variable, and many built-ins read it when they are given no argument. -
What is the loop variable of
foreach my $x (@list)?Answer
An alias to the element, so assigning to it changes the array
The variable is another name for the storage, which is why
$x =~ s/.../.../rewrites the array itself. -
Why does
for (1..3) { $_ *= 10 }leave nothing changed in the program?Answer
The range operator returns copies, so the alias points at a temporary list
A literal list is a temporary, so changing its elements changes nothing that survives the loop.
-
When should you name the loop variable instead of using
$_?Answer
Once the body is longer than a few lines, and in nested loops
A name tells the reader what the element is, and nested loops stop overwriting one default variable.
-
What does
if (/error/)test inside a loop that uses the default variable?Answer
The current element in
$_A pattern match without an explicit
=~runs against$_, which is the idiom behind most one-liners. -
What does this program print?
my @langs = qw(perl ruby); foreach my $l (@langs) { print uc $l, "\n" }Answer
PERL / RUBY
The loop visits each name and
ucuppercases it before the print. -
What does this program print?
foreach (1..3) { print "$_ " } print "\n";Answer
1 2 3
The range has three elements and each is printed with the space of the string.
-
What does this program print?
my @n = (1, 2, 3); $_ *= 10 for @n; print "@n\n";Answer
10 20 30
The array is real storage, so
$_is an alias to each element and the multiplication lands in the array. -
What does this program print?
my @f = qw(a.log b.log); for my $f (@f) { $f =~ s/\.log$/.txt/; } print "@f\n";Answer
a.txt b.txt
The named variable is an alias, so the substitution rewrites both elements of the array.
Article author: Arthur Isaev