foreach and the default variable

Contents
foreach over a list
The default variable
It is an alias
Name the element

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

Related articles
Perl
Perl course: zero to hero in 50 lessons
What is Perl and where it runs
Install Perl and check the version
Your first Perl script
The debugger as a REPL
Scalars and sigils
Numbers
Strings
Interpolation and quoting
Arrays
push, pop, shift and splice
Hashes
keys, values, exists and delete
Scalar and list context
Conditions and comparison
while, for, next and last
foreach and the default variable
Subroutines
Arguments in @_
References
Nested data structures
Regular expressions: match and anchors
Captures and named groups
Substitution with s///
split and join
grep and map
Sort and the Schwartzian transform
Read and write files
File tests and metadata
Directories and paths
die, warn and eval
Modules and Exporter
CPAN and cpanm
Objects with bless
Modern objects with Moo
Testing with Test::More
strict, warnings and diagnostics
Options with Getopt::Long
Environment and %ENV
system, backticks and pipes
One-liners with -n and -p
CSV and TSV processing
JSON with JSON::PP
HTTP clients with HTTP::Tiny
Sockets and IO::Socket
Databases with DBI
Capstone: todo CLI
Capstone: log report
Performance and profiling
Modern Perl tour
Hero roadmap: the whole course on one page
Install Perl on Windows 11
Install Perl on Ubuntu
Install Perl on Rocky Linux
Install Perl on macOS
Install Perl on FreeBSD
Perl in Docker

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: