perl exit loop example

Perl Exit Loop Example

To exit a loop in Perl, you can use the last statement. The last statement is used to terminate the loop immediately and resume execution after the loop. Here's an example of how to use the last statement to exit a loop in Perl:

foreach my $item (@array) {
    if ($item == $target) {
        last; # exit the loop
    # do something with $item

In the example above, the loop iterates over each element in the @array. If the current element matches the $target, the last statement is executed, and the loop is terminated.

Please note that the last statement can only be used within a loop construct such as foreach, while, or until. It cannot be used outside of a loop.

I hope this example helps! Let me know if you have any further questions.