while, for, next and last
| 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