How to break out of a loop in Perl

Overview

A loop is a sequence of instructions that are continuously executed until certain conditions are met. In some cases, we may want to break the loop before the given conditions are met. In Perl, we have the last keyword to break out of the loop.

Syntax

last

The last keyword will allow us to break out of the current enclosing loop.

last LABEL_NAME

If we specify LABEL_NAME, we can break out of the entire label containing the loop(s). This is usually used in nested loops.

Example 1

We will loop through an array, ages, and break out of the loop when a certain condition is met.

# array of ages
@ages = (25, 60, 40, 10, 30, 55, 76, 34);
# for loop
for my $age (@ages){
if($age==30){
#break the loop
last;
}
print "$age \n";
}

Explanation

  • Line 2: We declare and initialize an array, @ages.
  • Line 5: We use a for loop to traverse each element in the array, @ages.
  • Line 6: We check if the current element in the array, $age, is equal to 30.
  • Line 8: If the condition above is met, we break out of the loop using the last keyword.
  • Line 10: Otherwise, we print the current element of the array, ages.

Example 2

We will loop through the array, @scores1. Within this loop, we will loop through another array, @scores2. We will break out of both the loops within LABEL when a certain condition is met.

@scores1 = (25, 60, 40, 10, 30, 55, 76, 34);
@scores2 = (24, 59, 39, 10, 29, 54, 75, 33);
SCORES: {
for my $elem1 (@scores1) {
for my $elem2 (@scores2) {
if ($elem1 eq $elem2) {
print "$elem1";
last SCORES;
}
}
}
}

Explanation

  • Lines 1–2: We declare and initialize two arrays, @scores1, and @scores2.
  • Line 4: We defined a label, SCORES.
  • Line 5: We use a for loop to traverse each element of @scores1.
  • Line 6: We use a nested for loop to traverse each element of @scores2.
  • Line 7: Within this nested loop, we check whether the current element, $elem1, of the @scores1array is equal to the current element, $elem2, of the @scores2 array.
  • Lines 8–9: If the condition above is met, we print the element, $elem1 of @scores1 that matches the current element of @scores2. Next, we break out of both the loops within the label, SCORES, by using last SCORES. Otherwise, we do nothing.

Free Resources