Please tell me how to define a new operator in Raku, for example, how would one implement an arrow operator defined something like this:
operator ▶ {my ($left, $right) = @_; $left->{$right}}
Please tell me how to define a new operator in Raku, for example, how would one implement an arrow operator defined something like this:
operator ▶ {my ($left, $right) = @_; $left->{$right}}
It's fairly simple:
sub infix:<▶> ($left, $right) {
$left."$right"()
}
# Example:
class Foo {
method bar { "hello" }
}
my $a = Foo.new;
say $a ▶ 'bar'
# hello
The sub infix:< > defines new infix operators (other options are prefix, postfix, circumfix, and postcircumfix, the latter two require an opening and closing part, like <( )> for open and close parentheses).
The ($left, $right), as the name suggests, handle the left and right side values.
To call a method based on an string, you use the structure ." "() with the method name in quotation marks and followed by parentheses — even if there are no arguments. In this case, we just insert the variable for basic interpolation, although more complex operations are possible.