从不是例程的块返回CATCH移相器中的值的语法是什么?
sub foo() {
<1 2 3>.map: -> $a {
die 'oops';
CATCH { default { 'foo' } }
}
}
sub bar() {
<1 2 3>.map: -> $a {
die 'oops';
CATCH { default { return 'bar' } }
}
}
say foo(); # (Nil, Nil, Nil)
say bar(); # Attempt to return outside of immediatelly-enclosing Routine (i.e. `return` execution is outside the dynamic scope of the Routine where `return` was used)
Run Code Online (Sandbox Code Playgroud)
编辑:所需的输出是:
say baz(); # (baz baz baz)
Run Code Online (Sandbox Code Playgroud)
用例是map荷兰国际集团一个Seq与间歇抛出异常,处理通过返回一个缺省值来映射在块内的例外的方法.
返回退出功能范围,但您在其中使用它的方式bar()有两个功能在起作用.
bar()方法本身.这意味着你的回报是模棱两可的(好吧,至少对某些人来说),编译器会犹豫不决.
如果没有"返回",则将值foo()作为块内的常量处理,并且块返回Nil.这意味着foo()你有效地避免了解析其含义return,有效地推动了Nil堆栈.
这就是为什么你Nil在捕获的输出中有3 秒的原因foo().因为bar()目前还不清楚你是否希望bar()在第一个抛出的异常上终止例程的执行,或者你只是想将CATCH块推送到堆栈'bar'的非Nil值传回.
稍微修改过的代码版本
#!/bin/env perl6
sub foo() {
<1 2 3>.map: -> $a {
die 'oops';
}
CATCH { default { 'foo' } }
}
sub bar() {
<1 2 3>.map: -> $a {
die 'oops';
}
CATCH { default { return 'bar' } }
}
say foo();
say bar();
Run Code Online (Sandbox Code Playgroud)
可能会使这一点更清楚.它的输出是
[edwbuck@phoenix learn_ruby]$ ./ed.p6
Nil
bar
Run Code Online (Sandbox Code Playgroud)