Wait the light to fall

创建操作符

焉知非鱼

通过使用 sub 关键字后跟 prefix, infix, postfix, circumfix, 或 postcircumfix; 声明运算符; 然后是冒号结构中的冒号和运算符名称。对于(后)环缀操作符,用空格分隔这两部分。

sub hello {
    say "Hello, world!";
}
 
say &hello.^name;   # OUTPUT: «Sub␤» 
hello;              # OUTPUT: «Hello, world!␤» 
 
my $s = sub ($a, $b) { $a + $b };
say $s.^name;       # OUTPUT: «Sub␤» 
say $s(2, 5);       # OUTPUT: «7␤» 
 
# Alternatively we could create a more 
# general operator to sum n numbers 
sub prefix:<Σ>( *@number-list ) {
    [+] @number-list
}
 
say Σ (13, 16, 1); # OUTPUT: «30␤» 
 
sub infix:<:=:>( $a is rw, $b is rw ) {
    ($a, $b) = ($b, $a)
}
 
my ($num, $letter) = ('A', 3);
say $num;          # OUTPUT: «A␤» 
say $letter;       # OUTPUT: «3␤» 
 
# Swap two variables' values 
$num :=: $letter;
 
say $num;          # OUTPUT: «3␤» 
say $letter;       # OUTPUT: «A␤» 
 
sub postfix:<!>( Int $num where * >= 0 ) { [*] 1..$num }
say 0!;            # OUTPUT: «1␤» 
say 5!;            # OUTPUT: «120␤» 
 
sub postfix:<>( $a ) { sayI love $a!}
42;               # OUTPUT: «I love 42!␤» 
 
sub postcircumfix:<⸨ ⸩>( Positional $a, Whatever ) {
    say $a[0], '', $a[*-1]
}
 
[1,2,3,4]*;      # OUTPUT: «1…4␤» 
 
constant term:<> = ""; # We don't want to quote "love", do we? 
sub circumfix:<α ω>( $a ) {
    say$a is the beginning and the end.};
 
αω;               # OUTPUT: «♥ is the beginning and the end.␤»