last, next and Labels
Sometimes you need to leave a loop early or skip part of it. Perl's loop-control keywords are named for what they do:
| Keyword | C equivalent | Effect |
|---|---|---|
last |
break |
exit the loop immediately |
next |
continue |
skip to the next iteration |
redo |
none | restart the current iteration without re-checking the condition |
They work in while, until, for and foreach loops, and in bare blocks.
last: stop searching
use strict;
use warnings;
my @readings = (12, 15, 11, -999, 14, 13); # -999 marks the end of valid data
my $sum = 0;
my $count = 0;
for my $r (@readings) {
last if $r == -999;
$sum += $r;
$count++;
}
print "Used $count readings, average ", $sum / $count, "\n";Used 3 readings, average 12.6666666666667
next: skip what you don't want
use strict;
use warnings;
my @lines = ("# config file", "host=example.org", "", "port=8080", "# end");
for my $line (@lines) {
next if $line eq ""; # skip blank lines
next if $line =~ /^#/; # skip comments
my ($key, $value) = split /=/, $line;
print "$key -> $value\n";
}host -> example.org
port -> 8080
Putting next checks at the top of a loop body, as filters, keeps the main logic unindented and easy to read.
Labels for nested loops
last and next affect the innermost loop. To control an outer loop, give it a label (an uppercase name followed by a colon) and name it:
use strict;
use warnings;
my @grid = (
[1, 3, 5],
[7, 8, 9],
[2, 4, 6],
);
ROW: for my $r (0 .. $#grid) {
for my $c (0 .. $#{ $grid[$r] }) {
if ($grid[$r][$c] % 2 == 0) {
print "First even number $grid[$r][$c] at row $r, column $c\n";
last ROW;
}
}
}
LINE: for my $word (qw(apple b4d grape p34r melon)) {
for my $ch (split //, $word) {
next LINE if $ch =~ /\d/; # reject words containing digits
}
print "ok: $word\n";
}First even number 8 at row 1, column 1
ok: apple
ok: grape
ok: melon
Without the label, last would only end the inner loop over columns and the search would carry on in the next row.
Infinite loop with last
A common pattern for "loop until something happens" is while (1) with a last inside:
use strict;
use warnings;
my @attempts = (500, 503, 200);
my $tries = 0;
while (1) {
my $status = shift @attempts;
$tries++;
print "Try $tries: HTTP $status\n";
last if $status == 200;
last if $tries >= 5;
}
print "Done after $tries tries\n";Try 1: HTTP 500
Try 2: HTTP 503
Try 3: HTTP 200
Done after 3 tries
The continue block
A while loop may have a continue block that runs after each iteration, even when next is used. It is a good place for counter updates:
use strict;
use warnings;
my $i = 0;
while ($i < 6) {
next if $i % 2; # skip odd numbers
print "even: $i\n";
} continue {
$i++; # runs every time, also after next
}even: 0
even: 2
even: 4
Without the continue block, putting $i++ at the end of the body would be skipped by next, and the loop would never end.
Note:
lastandnextdo not work insidedo { } whileblocks (they are not real loops), and they should never be used inside the blocks ofmap,greporsort. Use a real loop there.
Test yourself
Which keyword skips the rest of the current iteration?
lastnextredoskip
How do you leave an outer loop from inside an inner one?
last last;break 2;- Label the outer loop and use
last LABEL; - It is not possible
When does a continue { } block after a while loop run?
- Only when the loop finishes
- After every iteration, including those ended by
next - Only after
last - Before the first iteration