How to break out of a loop in Perl with code example

This tutorial explains multiple ways to break and exit from a loop in Perl loops.

Many programming languages provide break keywords to exit from a loop. Perl has the last to exit from the loop.

Perl provides multiple ways to loop iteration using for, foreach, while, and do while syntax.

for loop with last to exit from the loop

  • Created an array of strings initialized in Perl
  • Iterated array using for loop
  • Each iteration does the following things
    • Checks current string is three and exits from the loop
    • Print the current string for each iteration

Here is foreach last example

my @numbers=("one","two","three");
for my $item (@numbers){
    if ($item eq "three"){
         last;
    }
    print "$item,\n"
}

foreach loop with last to exit from the loop

  • Created an array of strings
  • Iterated array using for each loop
  • Each iteration does the following things
    • Checks current string is three and exits from the loop
    • Print the current string for each iteration

Here is foreach last example

my @numbers=("one","two","three");
foreach my $item (@numbers){
    if ($item eq "three"){
         last;
    }
    print "$item,\n"
}

Perl While Loop’s last example

  • Created an array of strings
  • Iterated array using while loop
  • If the condition is passed, Do each iteration and do the following things
    • Checks current string is three, and exits from the loop
    • Print the current string for each iteration

Here is while last example

my @numbers=("one","two","three");
my $counter=0;
my $size=@numbers; ## get size
while($counter <$size){
    if (@numbers[$counter] eq "three"){
last;
}
print "@numbers[$counter],\n";
$counter=$counter+1;
}

Perl Do While Loop last example

  • Array variable created with initiated an strings
  • Iterated array using do while loop and it executes code block at least one time
  • If the condition is passed, Do each iteration and do the following things
    • Checks current string is three, and exits from the loop
    • Print the current string for each iteration

Here is while last example

my @numbers=("one","two","three");
my $counter=0;
my $size=@numbers; ## get size
do {
    if (@numbers[$counter] eq "three"){
last;
}
print "@numbers[$counter],\n";
$counter=$counter+1;
} while($counter <$size);