http://www.perlmonks.org?node_id=161082

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

Hello,

I've got a problem with Activeperl Built 631 (Win2k) with a next-statement.

If I execute it like the following:

C:\ce3\bin>perl -w my @list = qw(0 1 2 3 4 5); foreach (@list){ next if $_ == 0; print $_, " "; } ^Z 1 2 3 4 5
everything works fine.

But if I try the following:

C:\ce3\bin>perl -w use strict; my @list = qw(0 1 2 3 4 5); foreach (@list){ { next if $_ == 0; } print $_, " "; } ^Z 0 1 2 3 4 5

On the other hand, this works fine:

C:\ce3\bin>perl -w my @list = qw(0 1 2 3 4 5); foreach (@list){ { next if $_ == 0; print $_, " "; } } ^Z 1 2 3 4 5
Is this a perl bug, or am I the bug?

The same behaviour happens with Perl 5.005_03 under Solaris.

Best regards,
perl -le "s==*F=e=>y~\*martinF~stronat~=>s~[^\w]~~g=>chop,print"

Replies are listed 'Best First'.
Re: next in block in foreach-loop
by danger (Priest) on Apr 22, 2002 at 16:03 UTC

    A bare block is a loop that executes once but obeys loop control statements such as last, next, and redo. Thus, when you next in the bare-block inside your loop, you are next'ing out of the bare-block, not the outer loop.

Re: next in block in foreach-loop
by erikharrison (Deacon) on Apr 22, 2002 at 16:07 UTC

    The problem is an extra set of braces you are using in the second bit of code there. You have a nested bare block inside the foreach, the next breaks out of it, NOT the foreach.

    use strict; my @list = qw(0 1 2 3 4 5); foreach (@list){ #opens up the foreach block . . . { #opens up a new block . . . next if $_ == 0; #breaks out of enclosing block } #meaning it breaks to here. print $_, " "; #so '0' get's printed anyway } #ends the foreach

    Be careful about these extra blocks by using labels and explicitly breaking with them. Labels are goood practice for complicated loop structures anyway, for clarity's sake.

    Cheers,
    Erik
Re: next in block in foreach-loop
by broquaint (Abbot) on Apr 22, 2002 at 16:04 UTC
    You can use loop control functions within blocks (be they bare or named) e.g
    { print "enter option here: "; chomp(my $answer = <STDIN>); redo if $answer ne "quit"; }
    So the your example code is behaving as expected.
    HTH

    broquaint

Re: next in block in foreach-loop
by particle (Vicar) on Apr 22, 2002 at 16:32 UTC
    broquaint and erikharrison both mentioned labels, but neither provided an example. here's one:

    my @list = qw(0 1 2 3 4 5); LOOP: foreach (@list){ { next LOOP if $_ == 0; print $_, " "; } }
    this should behave as expected.

    ~Particle ;Þ