raku - 如何从 block 的CATCH相位器返回值?

标签 raku rakudo

从非例程的块中从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)

编辑:所需的输出是:
say baz(); # (baz baz baz)

用例是map用一种间歇性抛出异常的方法对Seq进行编码,并通过返回默认值来处理传递给map的块中的异常。

最佳答案

Return退出功能范围,但是在bar()中使用它的方式有两个作用。

  • bar()方法本身。
  • 您将返回值嵌入其中的lambda。

  • 这意味着您的返回是模棱两可的(至少对于某些人而言如此),并且编译器将不知所措。

    如果没有“返回”,foo()中的值将在该块内作为常量处理,并且该块返回Nil。这意味着在foo()中,您可以有效地避免解析return的含义,从而有效地将Nil压入堆栈。

    这就是为什么在Nil的捕获输出中有3 foo()的原因。对于bar(),不清楚是要在第一个抛出的异常时终止bar()例程的执行,还是只想将'bar'作为CATCH块压入堆栈的非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();
    

    可能会使这一点更加清楚。它的输出是
    [edwbuck@phoenix learn_ruby]$ ./ed.p6 
    Nil
    bar
    

    关于raku - 如何从 block 的CATCH相位器返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49890043/

    相关文章:

    raku - Apocalypse #1 中引入的 "semantic model"是什么?

    debugging - 为什么我不能命名无符号变量 v+digit?

    32-bit - Rakudo x86 32 位预编译安装程序/二进制文件在哪里?

    raku - 我在哪里可以了解 perl6 类型变量 (::T)

    exception - 控制或曾经与最后一团糟?

    object - 有谁知道为什么 TWEAK 例程在 BUILD 例程之前被命中?

    grammar - 如何将参数传递给 Perl 6 语法?

    raku - "require"定义在哪里?

    regex - 为什么我使用这些 Raku 正则表达式得到不同的回溯?

    raku - 重新编译nqp后为`Missing or wrong version of dependency`