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

8.1. last and next

Within the while and for loops one can use two special commands, called last and next. last terminates a loop prematurely while next skips the rest of the remaining loop body, skips to the loop condition and if it is met, executes the loop again.

By default, last and next operate 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 last or next.

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

print "Please enter a string:\n";

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

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

    if ($char ne "a")

    # Increment the 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";
    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 = <>;

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 next uses it as a parameter. All in all, next and last are 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