Question

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"

Was it helpful?

Solution

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';
    }
}

OTHER TIPS

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';
    }
}

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top