views:

120

answers:

3

When I run this:

use feature ':5.10';
$x=1;
given ($x) {
    when(1) {
        say '1';
        $x = 2;
        continue;
    }
    when (2) {
        say '2';
    }
}

This should print both 1 and 2, but it only prints 1. Am I missing something?

EDIT:

I have added $x = 2 and it still prints only "1"

+4  A: 

I think you may be misunderstanding the purpose of continue or the nature of fallthrough in a switch construct.

Every when block ends with an implicit break, so the given is exited upon a successful match. All continue does is tell the given block to continue processing the when conditions and not break out. It doesn't force the next when condition to magically be true when it isn't.

Consider this, which does output twice.

use feature ':5.10';
$x=1;
given ($x) {
    when(1) {
        say '1';
        continue;
    }
    when ( /1/ ) {
        say '1 again';
    }
}
friedo
see my edit... still not working
JoelFan
I think the source of my misunderstanding was C, where fall-through in "switch" does not do any additional testing... it just falls through and executes the next block.
JoelFan
+9  A: 

See the perlsyn man page:

given(EXPR) will assign the value of EXPR to $_ within the lexical scope of the block

This code outputs 1 and 2:

use feature ':5.10';
$x=1;
given ($x) {
    when(1) {
        say '1';
        $_ = 2;
        continue;
    }
    when (2) {
        say '2';
    }
}
mikegrb
A: 

Since given is not a loop construct (despite it supporting continue, which is special cased in that instance), use foreach or for like so:

use feature ':5.10';
$x=1;
for ($x) {
    when(1) {
        say '1';
        $x = 2;
        continue;
    }
    when (2) {
        say '2';
    }
}

for (expression) sets $_ to the expression, and that behaviour was used to emulate switch in some cases, before given/when.

MkV
This is so totally wrong, I'm not sure where to begin.
Brad Gilbert