In this tutorial, we will learn about the last statement in Perl. We will cover the basics of using the last statement to exit loops prematurely.
A last statement is used to exit a loop prematurely in Perl. When a last statement is encountered, it immediately exits the innermost loop it is in.
The syntax for the last statement in Perl is:
last;
The last statement can be used in for, foreach, while, and until loops to exit the loop prematurely.
$_
is equal to 5.$_
.foreach (1..10) {
if ($_ == 5) {
last;
}
print $_ . " ";
}
1 2 3 4
$i
and initialize it to 1.$i
is less than or equal to 10.$i
is equal to 5.$i
.$i = 1;
while ($i <= 10) {
if ($i == 5) {
last;
}
print $i . " ";
$i++;
}
1 2 3 4