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.4. Labeled Blocks

What if you want to jump out of the block that contains the innermost block, or to put it another way, exit from two nested blocks at once? In C, you'd resort to that much maligned goto to get you out. No such kludge is required in Perl; you can use last, next, and redo on any enclosing block by giving the block a name with a label.

A label is yet another type of name from yet another namespace following the same rules as scalars, arrays, hashes, and subroutines. As we'll see, however, a label doesn't have a special prefix punctuation character (like $ for scalars, & for subroutines, and so on), so a label named print conflicts with the reserved word print and would not be allowed. For this reason, you should choose labels that consist entirely of uppercase letters and digits, which will never be chosen for a reserved word in the future. Besides, using all uppercase stands out better within the text of a mostly lowercase program.

Once you've chosen your label, place it immediately in front of the statement containing the block followed by a colon, like this:

SOMELABEL: while (condition) {
    statement;
    statement;
    statement;
    if (nuthercondition) {
        last SOMELABEL;
    }
}

We added SOMELABEL as a parameter to last. This tells Perl to exit the block named SOMELABEL, rather than just the innermost block. In this case, we don't have anything but the innermost block. But suppose we had nested loops:

OUTER: for ($i = 1; $i <= 10; $i++) { INNER: for ($j = 1; $j <= 10; $j++) ...

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