"Perl for Perl Newbies" - Part 1The While Looplast and next

8.1. last and next

Within the whileand forloops one can use two special commands, called lastand next. lastterminates a loop prematurely while nextskips the rest of the remaining loop body, skips to the loop condition and if it is met, executes the loop again.

By default, lastand nextoperate on the most innermost loop. However, the loop to which they relate can be controlled by labelling the requested loop and specifying this label as a parameter to lastor next.

The following example is a rewrite of the "All A's" program using last:

print
"Please enter a string:
\n
";
$string=<>;
chomp(
$string);

# The first position in the string.
$position =
0;

while (
$position <
length(
$string))
{

$char =
lc(
substr(
$string,
$position,
1));


if (
$char
ne
"a")
    {

last;
    }


# Increment the position

$position++;
}

# If the position is the end of the string it means the loop was not
# terminated prematurely, so an "a" was not encountered.
if (
$position ==
length(
$string))
{

print
"The string you entered is all A's!
\n
";
}
else
{

print
"At least one of the characters in the string " .

"you entered is not 
\"
A
\"
.
\n
";
}

This program prints a left-tilted pyramid:

print
"Please enter the length of the pyramid:
\n
";
$size = <>;
chomp(
$size);

ROW_LOOP:
for
$row (
1 ..
$size)
{

for
$column (
1 .. (
$size+
1))
    {

if (
$column >
$row)
        {

print
"
\n
";

next ROW_LOOP;
        }

print
"#";
    }
}

"ROW_LOOP" is the label for the outer loop, and it can be seen that nextuses it as a parameter. All in all, nextand lastare sometimes very convenient (but don't tell it to Edsger W. Dijkstra's face!), so you will see them being used often.


Written by Shlomi Fish