Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

The following next behavior was brought to my attention:
#!/usr/bin/perl use strict; use warnings; foreach (1..5) { print "In for stmt\n"; { next; } print "end of for stmt\n"; } print "done.\n";

In the above -- why does "end of stmt" get printed?

Alternatively, why isn't the following an error?

if (1) { print "In if stmt\n"; { next; } print "end if for stmt\n"; } print "done.\n";

I would guess that the above implies that anonymous lexical scope is internally implemented as a foreach (1). Is that right? I am using perl 5.10.

Replies are listed 'Best First'.
Re: next and anonymous blocks
by kennethk (Abbot) on Mar 15, 2011 at 19:55 UTC
    From next:
    Note that a block by itself is semantically identical to a loop that executes once. Thus next will exit such a block early.

    So your guess is essentially correct, though literal internal implementation is likely not that simple.

Re: next and anonymous blocks
by jwkrahn (Abbot) on Mar 15, 2011 at 20:43 UTC
    the above implies that anonymous lexical scope is internally implemented as a foreach (1).

    foreach implies that $_ is affected which is not the case here.