O'Reilly logo

Learning Perl, Second Edition by Randal L. Schwartz, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

9.1. The last Statement

In some of the previous exercises you may have thought, "If I just had a C break statement here, I'd be done." Even if you didn't think that, let me tell you about Perl's equivalent for getting out of a loop early: the last statement.

The last statement breaks out of the innermost enclosing loop block,[1] causing execution to continue with the statement immediately following the block. For example:

while (something) {
    something;
    something;
    something;
    if (somecondition) {
        somethingorother;
        somethingorother;
        last; # break out of the while loop
    }
    morethings;
    morethings;
}
# last comes here

[1] Note that the do {} while/until construct does not count as a loop for purposes of next, last, and redo.

If somecondition is true, the somethingorother's are executed, and then last forces the while loop to terminate.

The last statement counts only looping blocks, not other blocks that are needed to make up some syntactic construct. This means that the blocks for the if and else statements, as well as the ones for do {} while/until, do not count; only the blocks that make up the for, foreach, while, until, and "naked" blocks count. (A naked block is a block that is not part of a larger construct such as a loop, subroutine, or an if/then/else statement.)

Suppose we wanted to see whether a mail message that had been saved in a file was from merlyn. Such a message might look like this:

From: merlyn@stonehenge.com (Randal L. Schwartz) To: stevet@ora.com Date: 01-DEC-94 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required