How to use last to exit a loop in Perl?

Question

How to use last to exit a loop in Perl?

In Perl, the last keyword is used to immediately exit a loop, similar to break in other programming languages. When last is executed inside a loop, the program stops looping and jumps to the first statement after the loop. This makes last very useful for controlling flow when a certain condition is met and you want to exit early.

How last Works in Perl Loops

Perl supports several types of loops: while, for, foreach, and until. In all of these, last will immediately exit the loop regardless of the loop’s condition or iteration count.

Here is the behavior summarized:

  • last exits the innermost loop it is called from.
  • If used in nested loops, it only exits the current (most inner) loop by default.
  • You can label loops and use last LABEL to exit an outer loop explicitly.

Simple Example Using last

This example loops from 1 to 10 but exits early when the counter reaches 5:

#!/usr/bin/perl
use strict;
use warnings;

for my $i (1..10) {
    print "Iteration $i\n";
    
    # Exit loop if $i equals 5
    last if $i == 5;
}
print "Loop ended.\n";

Explanation:

  • The for loop iterates from 1 to 10.
  • On each iteration, the current number is printed.
  • When $i equals 5, last exits the loop.
  • "Loop ended." is printed after the loop.

Output of the Above Code

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Loop ended.

Using last with Nested Loops and Labels

Perl also lets you label loops to exit outer loops from inside nested loops. Here is how:

#!/usr/bin/perl
use strict;
use warnings;

OUTER: for my $i (1..3) {
    INNER: for my $j (1..5) {
        print "i=$i, j=$j\n";
        
        # Exit the OUTER loop entirely when $j equals 3
        last OUTER if $j == 3;
    }
}
print "Nested loops ended.\n";

This code will exit both loops immediately once $j == 3, thanks to the last OUTER statement.

Perl Concepts Highlighted

  • TMTOWTDI ("There’s more than one way to do it"): You can use last in various loop types interchangeably.
  • Sigils: Notice use of $ for scalars like $i, $j.
  • Context: The last keyword does not return a value and controls loop flow.

Common Pitfalls

  • Forgetting to place last inside a loop causes a compile error.
  • Assuming last exits all nested loops unless you use a label.
  • Overusing last may lead to confusing flow; prefer clear conditions.

In summary, last is a straightforward and powerful way to abort a loop early in Perl. Use it to improve control flow readability and efficiency.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 5ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Loop ended.
STDERR
(empty)

Was this helpful?

Related Questions