Chapter 9. Miscellaneous Control Structures
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,[61] 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
If somecondition
is true, the
somethingorother
s are executed, and then
the 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. As a result, the blocks for the if
and
else
statement, as well as the one for a
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 otherwise part of a larger construct,
such as a loop, subroutine, or
if
/then
/else
statement.)
Suppose we wanted to see whether a mail message that had been saved in a file was from Erik. Such a message might look like:
From: eriko@axtech.com (Erik Olson) To: rdenn@ora.com Date: 01-MAY-97 08:16:24 PM MDT -0700 Subject: A sample mail message Here's the body of the mail message. ...
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.