SPUG: Using last in non-loop blocks
ced at carios2.ca.boeing.com
ced at carios2.ca.boeing.com
Thu Apr 22 18:46:05 CDT 2004
> According to perldoc -f last (perl 5.8.3):
>
> Note that a block by itself is semantically identical to a loop that
> executes once. Thus "last" can be used to effect an early exit out of
> such a block.
>
>This led me to think that I could safely use 'last' in any block
>structure, including an if block. E.g.,
>
> if ($reasonably_true) {
> #blah blah
> last unless $denominator > 0;
> #blah blah
> }
>
>I got slapped in the terminal with,
>
> Can't "last" outside a loop block at /my/dumb/script.pl line 162.
>
>Just thought that was interesting. I thought it should work (according to
>the docs anyway).
diagnostics provides an explanation:
Can't "last" outside a loop block at ./test1.pl line 6 (#1)
(F) A "last" statement was executed to break out of the current block,
except that there's this itty bitty problem called there isn't a current
block. Note that an "if" or "else" block doesn't count as a "loopish"
block, as doesn't a block given to sort(), map() or grep(). You can
usually double the curlies to get the same effect though, because the
inner curlies will be considered a block that loops once. See
perlfunc/last.
But that means something like this will work:
if ($reasonably_true) {{
#blah blah
last unless $denominator > 0;
#blah blah
}}
print "I managed to last out...\n";
--
Charles DeRykus
More information about the spug-list
mailing list