Loops are a fundamental part of programming, allowing us to repeatedly execute a set of instructions. However, there may be instances when we need to terminate a loop prematurely. In Perl, there are several ways to achieve this, and understanding these techniques is crucial for writing efficient and flexible code.

Image: www.educba.com
Using the ‘last’ Keyword
The ‘last’ keyword provides a straightforward and direct way to break out of a loop. When encountered, it immediately exits the innermost enclosing loop and continues execution with the statement following the loop.
my @numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9); foreach my $number (@numbers) if ($number > 5) last; print "$number ";
The above code iterates over the @numbers array and prints each element. However, once an element greater than 5 is encountered, the ‘last’ keyword is invoked, causing the loop to terminate. As a result, only the numbers 1, 2, 3, 4, and 5 are printed.
Utilizing ‘redo’ and ‘goto’
While ‘last’ abruptly exits the loop, Perl offers additional control mechanisms. The ‘redo’ keyword allows you to restart the current iteration of the loop, while ‘goto’ enables you to jump to a specific label within the loop.
my @names = ('John', 'Jane', 'Tom', 'Susan', 'Bob'); my $index = 0; LOOP: foreach my $name (@names) if ($index % 2 == 1) goto SKIP; # Skip odd indexes print "$name "; $index++; redo LOOP; # Repeat the current name SKIP:
In this example, ‘redo’ ensures that each name is printed twice, and ‘goto’ skips all odd indexes. As a result, the output becomes: “John John Jane Jane Tom Tom Susan Susan Bob Bob”.
Understanding Special Variables: $_ and $.
Perl provides special variables that enhance loop control. ‘$_’ holds the value of the current element in an array or hash during iteration, while ‘$.’ represents the current iteration counter. These variables can be leveraged for conditional breaking.
my %scores = ('John' => 95, 'Jane' => 80, 'Tom' => 75, 'Susan' => 90, 'Bob' => 85); foreach my $name (keys %scores) if ($_ > 90) print "$name has a score higher than 90\n"; last; # Exit if a score is greater than 90
The above code utilizes ‘$_’ to examine each score and exits the loop once a score exceeds 90. The output becomes: “John has a score higher than 90”.

Image: www.educba.com
Perl Break Out Of Loop
Conclusion