Perl Scripts ·

Breaking Out of Loops in Perl: last, next and Labels

By Manu Mathew, Technical Lead Engineer · Published 4 January 2014 · Last updated 5 October 2026

Isometric illustration of blocks circling a looped track, with a blue exit ramp leading off it

Loops often have a natural stopping point before the end: you have found the record you were looking for, or hit a value that means “stop”. This page brings together several short notes on breaking out of loops in Perl I wrote between 2013 and 2014. I have rewritten them in one place, with tested examples and current advice, so you don’t have to piece the answer together from fragments.

Quick answer

last leaves a loop straight away, and next skips to the next item. In nested loops, both act on the innermost loop unless you give the outer loop a label (such as ROW:) and write last ROW. Perl has no break keyword for this; last is the equivalent.

I tested each example with Perl 5.40, using use strict and use warnings.

How do I stop a loop as soon as a condition is met?

Call last; it works in for, foreach, while and until loops.

use strict;
use warnings;

my @numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 12);
my $stop_at = 3;

for my $n (@numbers) {
    print "$n\n";
    last if $n == $stop_at;    # leave the loop straight away
}
# 1
# 2
# 3

How do I stop searching once I have found a match?

Save the result, then call last so the loop doesn’t keep checking the remaining items.

use strict;
use warnings;

my @countries = ( { id => 91, name => 'India' }, { id => 44, name => 'United Kingdom' } );
my $wanted_id = 91;

my $country_name;
for my $c (@countries) {
    if ($c->{id} == $wanted_id) {
        $country_name = $c->{name};
        last;                  # found it, so stop looking
    }
}
print "$country_name\n";       # India

For a plain “find the first match”, first from List::Util does the same in one line: my $c = first { $_->{id} == $wanted_id } @countries;.

How do I skip one item and carry on?

next ends the current pass through the loop and moves on to the next item.

use strict;
use warnings;

for my $n (1 .. 6) {
    next if $n % 2;            # skip odd numbers and go to the next one
    print "$n\n";
}
# 2
# 4
# 6

How do I break out of nested loops?

Put a label before the outer loop and name it: last ROW leaves both loops at once.

use strict;
use warnings;

my @rows = ( [1, 2, 3], [4, -1, 6], [7, 8, 9] );

ROW:
for my $row (@rows) {
    for my $value (@$row) {
        if ($value < 0) {
            print "Found a negative value, stopping\n";
            last ROW;          # leaves both loops, not just the inner one
        }
        print "$value\n";
    }
}
# 1 2 3 4, then the message

Labels are usually written in capitals so they stand out. next ROW works the same way, moving on to the next outer row.

Does last work in while loops and do-while blocks?

last works in while loops, but not in a do { … } while block, which is not a real loop to Perl.

use strict;
use warnings;

my @queue = ('a', 'b', 'STOP', 'c');
while (defined(my $item = shift @queue)) {
    last if $item eq 'STOP';
    print "Processing $item\n";
}
print "Left in queue: @queue\n";   # Left in queue: c

If you need to leave a do { … } while, rewrite it as a while loop, or wrap it in an extra block with a label, as perlsyn explains.

Frequently asked questions

Does last work inside a grep or map block?

Not as you might expect. A grep or map block is not a loop, so last inside it leaves the nearest enclosing loop, or dies with “Can’t “last” outside a loop block” if there isn’t one. Use first from List::Util, or a plain foreach loop, when you need to stop early.

How do I leave a subroutine early instead of a loop?

Use return. It leaves the subroutine at once, even from inside a loop, and hands back a value. Calling last inside a subroutine to stop a loop in the calling code works, but Perl warns “Exiting subroutine via last”, so avoid it.

What does redo do?

redo restarts the current pass of the loop without checking the condition again or moving to the next item. It is rarely needed; code that seems to need it is usually clearer as a while loop with an explicit retry counter.

Can I use last inside an if block?

Yes, as long as the if block sits inside a loop. last acts on the nearest enclosing loop, or on the labelled one, never on the if block itself, so last if $done; is a common and readable way to stop.

Related notes: Perl arrays: length, add, remove and search; Perl hashes; reading a file with while or foreach; hiring a remote Perl developer.

Need help with Perl code?

If you have Perl code that needs fixing, extending or upgrading, I’m happy to take a look. I work remotely from Kozhikode, Kerala, with teams across India and elsewhere; Perl development and maintenance explains how I help. If you are deciding how to bring someone in, Hiring a remote Perl developer is a short checklist.

You can reach me through the contact section or email me at manu@manu.co.in. A few lines about the system and what you need is a good start.

Sources: perlfunc: last; perlfunc: next; perlsyn: loop control; List::Util: first.

Back to the blog