Labeled Blocks
What
if you want to jump out of the block that contains the innermost
block—to 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 makes an item stand out better
within the text of a mostly lowercase program.
After you’ve chosen your label, place it immediately in front of the statement containing the block, and follow it with a colon, like this:
SOMELABEL: while (condition
) {statement
;statement
;statement
; if (nuthercondition
) { last SOMELABEL; } }
We added SOMELABEL
as a parameter to
last
. This parameter tells Perl to exit the block
named SOMELABEL
, rather than exiting 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 <= ...
Get Learning Perl on Win32 Systems now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.