last statement - get out of repetition
You can use the last statement to get out of the next iteration. This corresponds to a C or Java break statement.
last
last statement can be used in loop syntax such as while statement and for statement.
while (1) { if (condition) { last; } } for (my $i = 0; $i < 10; $i++) { if (condition) { last; } } foreach my $animal (@animals) { if (condition) { last; } }
You can use last statement when you want to break out of the loop only under certain conditions.
Example program
This is an example program that uses last statement.
Exit the loop when a specific character is matched
In the middle of loop processing, you can use last statement when you want to exit the loop under certain conditions. This is an example that prepares array of characters and exits the loop for a specific character.
use strict; use warnings; my @chars = qw(z z a b c d e f); for my $char (@chars) { last if $char eq 'c'; print "$char\n"; }
This is the execution result. Since the loop is exited at "c", the output result is only the character before "c".
z z a b b
"Qw (z z a b c d e f)" is string list operator.
if statement, for statement, and while statement are explained in detail below, so please refer to them.
- Learn the syntax of conditional branch using if statement
- Let's learn the iterative processing using for statement and while statement
How to get out of multiple loops
You can use last to escape from a loop, but only the most recent loop block can escape. It takes some ingenuity to get out of multiple loops. You can get out of multiple loops by making good use of flags and conditionals.
A program that escapes an infinite loop using a flag and two lasts.
my $num = 0; # Escape from multiple loops while (1) { # Create one flag my $finish; while (1) { if ($num == 10) { $finish = 1; last; } $num ++; } if ($finish) { last; } }
You could write the label on top of the outer loop and exit the multiple loop as a "last label", but I personally don't recommend it. The source code will be better visible if you flag it well as described above and break out of multiple loops.
Related information
You can jump to the beginning of the loop using next statement
Similar to last statement is next statement. You can use next statement to move to the beginning of the next loop.
next
For next statement, refer to the following article.