Control flow

last#

Exit a loop immediately, skipping the rest of the body and the continue block.

last is Perl’s equivalent of C’s break. It transfers control out of the enclosing loop to the statement that follows it. The current iteration’s remaining statements do not run, and neither does the loop’s continue block — that is the key difference from next. With no argument it targets the innermost enclosing while, until, for, foreach, or bare block; with a LABEL it targets a named loop further out.

Synopsis#

last
last LABEL
last EXPR       # LABEL computed at runtime, since 5.18

What you get back#

Nothing. last performs flow control; it does not produce a value. It cannot be used to return a result from a block that normally yields one, such as eval { ... }, sub { ... }, or do { ... }. In those contexts either the construct produces no value or the program dies with Can't "last" outside a loop block — see Edge cases below.

Targeting a loop by label#

Without a label, last refers to the innermost enclosing loop. That is usually what you want:

while (my $line = <$fh>) {
    last if $line =~ /^__END__$/;
    process($line);
}

With a label you can break out of an outer loop from within a nested one. Labels are conventionally all-uppercase:

OUTER: for my $row (@grid) {
    for my $cell (@$row) {
        last OUTER if $cell eq 'STOP';
    }
}
# control resumes here

last EXPR (Perl 5.18+) computes the label at runtime. EXPR must evaluate to a string naming an enclosing label:

my $target = 'OUTER';
last $target;

Interaction with continue blocks#

A loop’s continue block normally runs at the end of every iteration, including the last. last skips it — that is its defining difference from next:

my $i = 0;
while ($i < 10) {
    last if $i == 3;
    print "body $i\n";
} continue {
    $i++;                 # runs after every iteration EXCEPT
                          # the one terminated by last
}
# prints body 0, body 1, body 2; then exits the loop.
# $i stays at 3 because continue did not fire the final time.

If you want continue to run, use next with a guard instead, or advance the counter before the last.

Behaviour in nested loops#

last only leaves one loop at a time — the innermost one, unless labelled. In this example the inner last exits the for but the while keeps running:

while (1) {
    for my $x (1 .. 5) {
        last if $x == 3;
    }
    # control lands here every iteration of the while
    last;                 # needed to exit the while as well
}

To unwind several levels at once, label the outer loop and target it:

SEARCH: for my $file (@files) {
    open my $fh, '<', $file or next;
    while (my $line = <$fh>) {
        if ($line =~ /$pattern/) {
            $found = $file;
            last SEARCH;  # exits both the while and the for
        }
    }
}

Bare blocks count as loops#

A bare { ... } block is, for flow-control purposes, a loop that executes exactly once. last can exit such a block early, which is the idiomatic way to write “try a sequence of checks, bail out on the first match”:

{
    last if $cached;
    recompute();
    store_in_cache();
}
# control continues here

This is the only last form that does not involve an iterating construct.

Examples#

Stop reading a file on a blank line — the classic header-terminator idiom:

LINE: while (<$fh>) {
    last LINE if /^$/;
    push @header, $_;
}

Find-and-report across a two-dimensional structure:

my $hit;
ROW: for my $r (0 .. $#grid) {
    for my $c (0 .. $#{ $grid[$r] }) {
        if ($grid[$r][$c] eq $needle) {
            $hit = [$r, $c];
            last ROW;
        }
    }
}

Early exit from a bare block used as a try-once sequence:

my $result;
{
    $result = $cache{$key}, last if exists $cache{$key};
    $result = compute($key);
    $cache{$key} = $result;
}

Computed label (Perl 5.18+). Rarely needed, but useful when the target loop is chosen dynamically:

my $level = $deep ? 'OUTER' : 'INNER';
OUTER: for (...) {
    INNER: for (...) {
        last $level if $done;
    }
}

Edge cases#

  • Illegal in grep and map. Both expect their block to produce a value for every input element; last precludes that. The parser accepts the code (the block is not lexically a loop it can see through), but executing it dies with Can't "last" outside a loop block. Filter with a conditional inside the block instead, or switch to an explicit for loop.

  • do { ... } is not a loop. last inside do { ... } does not terminate the do; it unwinds to the nearest enclosing real loop. If there is none, the program dies with Can't "last" outside a loop block. For early exit from a do used as an expression, see the workarounds in perlsyn under “Statement Modifiers” — typically a bare block plus last, or a one-shot for loop.

  • sub { ... } is not a loop. last inside a sub body does not return from the sub; it unwinds past the sub to the enclosing loop in the caller. Use return to leave a sub.

  • last inside eval does not escape the eval. eval { ... } is not itself a loop, so last looks outward past the eval for the nearest enclosing loop and unwinds to it. The eval is exited as a side effect of that unwind, but $@ is left empty — no exception was raised. If the eval has no enclosing loop above it, the program dies with Can't "last" outside a loop block. To leave an eval normally, fall off the end or use die (caught by the eval itself) or return (if the eval is inside a sub and you want to leave the sub).

  • Precedence. Unlike most named operators, last has the same precedence as assignment and is exempt from the looks-like-a-function rule. So last ("foo") . "bar" passes "foo" . "bar" as the label, not just "foo". Use a space, or omit the parentheses, to avoid surprises:

    last LABEL;
    last "LABEL";
    
  • Unknown label. last NOPE where no enclosing loop is tagged NOPE dies with Label not found for "last NOPE". This is a runtime error, not a compile-time one — the label is resolved against the dynamic call stack.

  • Loop modifier form has no block to exit. EXPR if COND and similar statement-modifier forms are not loops; last inside the expression unwinds past them.

Differences from upstream#

Fully compatible with upstream Perl 5.42.

See also#

  • next — skip to the next iteration, running the continue block first; the counterpart to last that keeps the loop alive

  • redo — restart the current iteration without re-testing the condition and without running continue

  • return — leave a subroutine with a value; the right tool when you reach for last inside sub { ... }

  • continue — the loop-trailer block that last skips and next honours; read its page for the three-way illustration of last / next / redo