When I run this:
use feature ':5.10';
$x=1;
given ($x) {
when(1) {
say '1';
$开发者_StackOverflow中文版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"
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';
}
}
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.
精彩评论