- publishing free software manuals
Perl Language Reference Manual
by Larry Wall and others
Paperback (6"x9"), 724 pages
ISBN 9781906966027
RRP £29.95 ($39.95)

Sales of this book support The Perl Foundation! Get a printed copy>>>

4.7 Loop Control

The next command starts the next iteration of the loop:

LINE: while (<STDIN>) {
    next LINE if /^#/;      # discard comments
    ...
}

The last command immediately exits the loop in question. The continue block, if any, is not executed:

LINE: while (<STDIN>) {
    last LINE if /^$/;      # exit when done with header
    ...
}

The redo command restarts the loop block without evaluating the conditional again. The continue block, if any, is not executed. This command is normally used by programs that want to lie to themselves about what was just input.

For example, when processing a file like /etc/termcap. If your input lines might end in backslashes to indicate continuation, you want to skip ahead and get the next record.

while (<>) {
    chomp;
    if (s/\\$//) {
        $_ .= <>;
        redo unless eof();
    }
    # now process $_
}

which is Perl short-hand for the more explicitly written version:

LINE: while (defined($line = <ARGV>)) {
    chomp($line);
    if ($line =~ s/\\$//) {
        $line .= <ARGV>;
        redo LINE unless eof(); # not eof(ARGV)!
    }
    # now process $line
}

Note that if there were a continue block on the above code, it would get executed only on lines discarded by the regex (since redo skips the continue block). A continue block is often used to reset line counters or ?pat? one-time matches:

# inspired by :1,$g/fred/s//WILMA/
while (<>) {
    ?(fred)?    && s//WILMA $1 WILMA/;
    ?(barney)?  && s//BETTY $1 BETTY/;
    ?(homer)?   && s//MARGE $1 MARGE/;
} continue {
    print "$ARGV $.: $_";
    close ARGV  if eof();           # reset $.
    reset       if eof();           # reset ?pat?
}

If the word while is replaced by the word until, the sense of the test is reversed, but the conditional is still tested before the first iteration.

The loop control statements don't work in an if or unless, since they aren't loops. You can double the braces to make them such, though.

if (/pattern/) {{
    last if /fred/;
    next if /barney/; # same effect as "last", but doesn't document as well
    # do something here
}}

This is caused by the fact that a block by itself acts as a loop that executes once, see 4.10.

The form while/if BLOCK BLOCK, available in Perl 4, is no longer available. Replace any occurrence of if BLOCK by if (do BLOCK).

ISBN 9781906966027Perl Language Reference ManualSee the print edition