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

    1. sub hello {
    2. say "Hello, world!";
    3. }
    4. say &hello.^name; # OUTPUT: «Sub
    5. »
    6. hello; # OUTPUT: «Hello, world!
    7. »
    8. my $s = sub ($a, $b) { $a + $b };
    9. say $s.^name; # OUTPUT: «Sub
    10. »
    11. say $s(2, 5); # OUTPUT: «7
    12. »
    13. # Alternatively we could create a more
    14. # general operator to sum n numbers
    15. sub prefix:<Σ>( *@number-list ) {
    16. [+] @number-list
    17. }
    18. say Σ (13, 16, 1); # OUTPUT: «30
    19. »
    20. sub infix:<:=:>( $a is rw, $b is rw ) {
    21. ($a, $b) = ($b, $a)
    22. }
    23. my ($num, $letter) = ('A', 3);
    24. say $num; # OUTPUT: «A
    25. »
    26. say $letter; # OUTPUT: «3
    27. »
    28. # Swap two variables' values
    29. $num :=: $letter;
    30. say $num; # OUTPUT: «3
    31. »
    32. say $letter; # OUTPUT: «A
    33. »
    34. sub postfix:<!>( Int $num where * >= 0 ) { [*] 1..$num }
    35. say 0!; # OUTPUT: «1
    36. »
    37. say 5!; # OUTPUT: «120
    38. »
    39. sub postfix:<♥>( $a ) { say I love $a!“ }
    40. 42♥; # OUTPUT: «I love 42!
    41. »
    42. sub postcircumfix:<⸨ ⸩>( Positional $a, Whatever ) {
    43. say $a[0], '…', $a[*-1]
    44. }
    45. [1,2,3,4]⸨*⸩; # OUTPUT: «1…4
    46. »
    47. constant term:<♥> = "♥"; # We don't want to quote "love", do we?
    48. sub circumfix:<α ω>( $a ) {
    49. say $a is the beginning and the end.“
    50. };
    51. α♥ω; # OUTPUT: «♥ is the beginning and the end.
    52. »