Perl loop - how to break out of a loop in Perl

Perl loop break FAQ: How do I break out of a Perl loop?

Problem: You're writing some Perl loop code (for, foreach, or while), and you have a condition where you need to break out of your loop early, and you quickly find out that Perl doesn't have a 'break' operator.

The Perl "break" statement

In many programming languages you use the break operator to break out of a loop like this, but in Perl you use the last operator to break out of a loop, like this:

last;

While using the Perl last operator instead of the usual break operator seems a little unusual, it can make for some readable code, as we'll see next.

A for loop example with last

Here's a Perl break/last example I just pulled out of an actual script. I simplified this a little bit, but in short, this foreach loop was intended to let me push 10 items onto an array named @tags, and then break out of the loop at that point:

my $counter = 1;
foreach $foo (sort {$importHash{$b} <=> $importHash{$a}} (keys %importHash))
{
  # push the string $foo onto the @tags array
  push @tags, $foo;
  
  # break out of our perl loop when the counter reaches 10
  last if ($counter++ == 10);
}

I really like the last/if syntax shown above, but I should note that you can also use the Perl last operator in a typical if/then statement if you prefer, like this:

if (SOME_TEST_CONDITION)
{
  # break out of our perl loop
  last;
}

Related - how to skip an element in a Perl loop

On a related note, if you just need to skip over the current loop iteration -- and stay in your Perl loop to work on the next element -- just use the Perl next operator, like this:

if (SOME_TEST_CONDITION)
{
  next;
}

For more information, here's a link to my Perl for loop 'next' tutorial. Otherwise, I hope this Perl break/last example has been helpful.