为什么我的 continue 不执行 Perl 5.10 中的下一个 when 块?
当我运行此命令时:
use feature ':5.10';
$x=1;
given ($x) {
when(1) {
say '1';
$x = 2;
continue;
}
when (2) {
say '2';
}
}
这应该打印 1 和 2,但它只打印 1。我错过了什么吗?
编辑:
我添加了 $x = 2 但它仍然只打印“1”
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"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请参阅 perlsyn 手册页:
此代码输出 1 和 2:
See the perlsyn man page:
This code outputs 1 and 2:
我认为您可能误解了
continue
的目的或 switch 构造中失败的本质。每个
when
块都以隐式中断结束,因此given
在成功匹配时退出。continue
所做的只是告诉given
块继续处理when
条件并且不中断。当下一个when
条件不为真时,它不会强制其神奇地为真。考虑一下这个,它确实输出两次。
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 thegiven
is exited upon a successful match. Allcontinue
does is tell thegiven
block to continue processing thewhen
conditions and not break out. It doesn't force the nextwhen
condition to magically be true when it isn't.Consider this, which does output twice.
由于给定不是循环构造(尽管它支持 continue,这在该实例中是特殊情况),请使用 foreach 或 for 像这样:
for(表达式)将 $_ 设置为表达式,并且该行为用于模拟某些中的 switch情况下,在给定之前/何时。
Since given is not a loop construct (despite it supporting continue, which is special cased in that instance), use foreach or for like so:
for (expression) sets $_ to the expression, and that behaviour was used to emulate switch in some cases, before given/when.