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.
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.
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 loopfor my $age (@ages){if($age==30){#break the looplast;}print "$age \n";}
@ages
.for
loop to traverse each element in the array, @ages
.$age
, is equal to 30
.last
keyword.ages
.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;}}}}
@scores1
, and @scores2
.SCORES
.for
loop to traverse each element of @scores1
.for
loop to traverse each element of @scores2
. $elem1
, of the @scores1
array is equal to the current element, $elem2
, of the @scores2
array.$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.