while, for, next and last

Contents
while and until
The C-style for
next, last, redo
Labels

while and until

while repeats a block as long as the condition is true. until is the same loop with the test reversed, which is handy for waiting on something that should eventually become true.

my $tries = 0; while ($tries < 3) { $tries++; print "try $tries\n"; } my $waited = 0; until ($waited >= 2) { $waited++ } print "waited $waited\n"; # waited 2

perl demo.pl

try 1
try 2
try 3
waited 2

A loop that never changes its condition never ends. When a script hangs, the first place to look is the variable in the while test: is anything inside the block able to move it?

The C-style for

The three-part for loop exists in Perl with the same meaning as in C: start, test, step. Use it when the counter itself matters, and foreach when you only need the elements.

for (my $i = 1; $i <= 3; $i++) { print "line $i\n"; }

perl demo.pl

line 1
line 2
line 3

Declaring the counter inside the parentheses keeps it out of the surrounding scope, which is one more reason to write for (my $i = ...) rather than a bare variable.

next, last, redo

Three keywords steer a loop from inside. next skips the rest of this pass, last leaves the loop entirely, and redo runs the same pass again without rechecking the condition.

for my $n (1..6) { next if $n % 2 == 0; # skip even numbers last if $n > 5; # stop after 5 print "$n "; } print "\n"; # 1 3 5

perl demo.pl

1 3 5

redo is rare and easy to misuse: it restarts the block without advancing the counter, so a loop that redoes without changing anything spins forever. Prefer a small inner loop when you need a retry.

Labels

Nested loops need a way to say which one to leave. Put a name and a colon before the outer loop, then use it with last or next.

OUTER: for my $row (1..3) { for my $col (1..3) { last OUTER if $row * $col == 4; print "$row$col "; } } print "\n";

perl demo.pl

11 12 13 21

Labels are written in capitals by convention, and only exist to be named by next, last or redo. The goto keyword exists too; treat it as a museum piece and restructure the code instead.

Next: foreach and the default variable

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: