Creating operators
Operators are declared by using the sub
keyword followed by
prefix
, infix
, postfix
, circumfix
, or postcircumfix
;
then a colon and the operator name in a quote construct. For (post-)circumfix
operators separate the two parts by white space.
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 ) { say āI 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.ā¤Ā»
These operators use the extended identifier syntax; that is what enables the use of any kind of codepoint to refer to them.