在 Raku 中定义新的中缀运算符

10 operators raku

请告诉我如何在 Raku 中定义一个新的运算符,例如,如何实现一个定义如下的箭头运算符:

operator ? {my ($left, $right) = @_; $left->{$right}}
Run Code Online (Sandbox Code Playgroud)

use*_*601 14

这很简单:

sub infix:<?> ($left, $right) {
  $left."$right"() 
}


# Example: 

class Foo {
  method bar { "hello" }
}

my $a = Foo.new;

say $a ? 'bar'
# hello
Run Code Online (Sandbox Code Playgroud)

sub infix:< >定义了新的中缀运算符(其他选项是prefixpostfixcircumfix,和postcircumfix,后两者需要的开闭部一样,<( )>用于打开和关闭括号)。

($left, $right),顾名思义,处理好左边和右边的值。

要调用基于字符串的方法,您可以使用." "()带有引号的方法名称和后跟括号的结构——即使没有参数。在这种情况下,我们只为基本插值插入变量,尽管更复杂的操作是可能的。