SPUG: Using last in non-loop blocks
Asim Jalis
asim at pair.com
Thu Apr 22 18:50:28 CDT 2004
On Thu, Apr 22, 2004 at 04:37:53PM -0700, Andrew Sweger 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).
Perhaps when the documentation says "a block by itself" it means
a block that is part of a construct such as "if".
So this throws an error as you observe:
/usr/home/asim> perl -e 'if(1){ print "1\n"; last; print "2\n"; }
'
1
Can't "last" outside a loop block at -e line 1.
But the following works just fine, and breaks out of the block
before printing "2", without an error.
/usr/home/asim> perl -e '{ print "1\n"; last; print "2\n"; }
'
1
Asim
More information about the spug-list
mailing list