SPUG: Using last in non-loop blocks
Yitzchak Scott-Thoennes
sthoenna at efn.org
Thu Apr 22 19:57:05 CDT 2004
On Thu, Apr 22, 2004 at 04:46:05PM -0700, ced at carios2.ca.boeing.com wrote:
> > 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";
It's worth noting that there is no way of doubling the braces for a
do { } while or do { } until block that will work sanely both for last
and next/redo.
More information about the spug-list
mailing list