|
4 | 4 |
|
5 | 5 | =SUBTITLE A short tutorial on how to declare operators and create new ones.
|
6 | 6 |
|
7 |
| -Operators are declared by C<sub> |
8 |
| -followed by C<prefix>, C<infix>, C<postfix>, C<circumfix>, or C<postcircumfix>; |
| 7 | +Operators are declared by using the C<sub> keyword followed by |
| 8 | +C<prefix>, C<infix>, C<postfix>, C<circumfix>, or C<postcircumfix>; |
9 | 9 | then a colon and the operator name in a quote construct. For (post-)circumfix
|
10 | 10 | operators separate the two parts by white space.
|
11 | 11 |
|
12 | 12 | sub hello {
|
13 | 13 | say "Hello, world!";
|
14 | 14 | }
|
| 15 | +
|
15 | 16 | say &hello.^name; # OUTPUT: «Sub»
|
16 | 17 | hello; # OUTPUT: «Hello, world!»
|
17 | 18 |
|
18 | 19 | my $s = sub ($a, $b) { $a + $b };
|
19 | 20 | say $s.^name; # OUTPUT: «Sub»
|
20 | 21 | say $s(2, 5); # OUTPUT: «7»
|
21 | 22 |
|
22 |
| - sub postfix:<♥>($a){ say „I love $a!“ } |
23 |
| - 42♥; |
24 |
| - # OUTPUT: «I love 42!» |
25 |
| - sub postcircumfix:<⸨ ⸩>(Positional $a, Whatever){ say $a[0], '…', $a[*-1] } |
26 |
| - [1,2,3,4]⸨*⸩; |
27 |
| - # OUTPUT: «1…4» |
| 23 | + # Alternatively we could create a more |
| 24 | + # general operator to sum n numbers |
| 25 | + sub prefix:<Σ>( *@number-list ) { |
| 26 | + [+] @number-list |
| 27 | + } |
| 28 | +
|
| 29 | + say Σ (13, 16, 1); # OUTPUT: «30» |
| 30 | +
|
| 31 | + sub infix:<:=:>( $a is rw, $b is rw ) { |
| 32 | + ($a, $b) = ($b, $a) |
| 33 | + } |
| 34 | +
|
| 35 | + my ($num, $letter) = ('A', 3); |
| 36 | + say $num; # OUTPUT: «A» |
| 37 | + say $letter; # OUTPUT: «3» |
| 38 | +
|
| 39 | + # Swap two variables' values |
| 40 | + $num :=: $letter; |
| 41 | +
|
| 42 | + say $num; # OUTPUT: «3» |
| 43 | + say $letter; # OUTPUT: «A» |
| 44 | +
|
| 45 | + sub postfix:<!>( Int $num where * >= 0 ) { [*] 1..$num } |
| 46 | + say 0!; # OUTPUT: «1» |
| 47 | + say 5!; # OUTPUT: «120» |
| 48 | +
|
| 49 | + sub postfix:<♥>( $a ) { say „I love $a!“ } |
| 50 | + 42♥; # OUTPUT: «I love 42!» |
| 51 | +
|
| 52 | + sub postcircumfix:<⸨ ⸩>( Positional $a, Whatever ) { |
| 53 | + say $a[0], '…', $a[*-1] |
| 54 | + } |
| 55 | +
|
| 56 | + [1,2,3,4]⸨*⸩; # OUTPUT: «1…4» |
| 57 | +
|
28 | 58 | constant term:<♥> = "♥"; # We don't want to quote "love", do we?
|
29 |
| - sub circumfix:<α ω>($a){ say „$a is the beginning and the end.“ }; |
30 |
| - α♥ω; |
31 |
| - # OUTPUT: «♥ is the beginning and the end.» |
| 59 | + sub circumfix:<α ω>( $a ) { |
| 60 | + say „$a is the beginning and the end.“ |
| 61 | + }; |
| 62 | +
|
| 63 | + α♥ω; # OUTPUT: «♥ is the beginning and the end.» |
32 | 64 |
|
33 | 65 | =end pod
|
34 | 66 |
|
|
0 commit comments