/
operators.pod6
2641 lines (1793 loc) · 84.6 KB
/
operators.pod6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
=begin pod :tag<perl6>
=TITLE Operators
=SUBTITLE Common Perl 6 infixes, prefixes, postfixes, and more!
See L<Sub> on how to define operators.
=head1 Operator Precedence
In an expression like C<1 + 2 * 3>, the C<2 * 3> is evaluated first
because the infix C<*> has tighter B<precedence> than the C<+>.
The following table summarizes the precedence levels in Perl 6, from
tightest to loosest:
=begin table
A | Level | Examples
==+==================+==========
N | Terms | 42 3.14 "eek" qq["foo"] $x :!verbose @$array
L | Method postfix | .meth .\+ .? .* .() .[] .{} .<> .«» .:: .= .^ .:
N | Autoincrement | \+\+ --
R | Exponentiation | **
L | Symbolic unary | ! \+ - ~ ? \| \|\| \+^ ~^ ?^ ^
L | Dotty infix | .= .
L | Multiplicative | * / % %% \+& \+< \+> ~& ~< ~> ?& div mod gcd lcm
L | Additive | \+ - \+\| \+^ ~\| ~^ ?\| ?^
L | Replication | x xx
X | Concatenation | ~
X | Junctive and | &
X | Junctive or | \| ^
L | Named unary | temp let
N | Structural infix | but does <=> leg cmp .. ..^ ^.. ^..^
C | Chaining infix | != == < <= > >= eq ne lt le gt ge ~~ === eqv !eqv =~=
X | Tight and | &&
X | Tight or | \|\| ^^ // min max
R | Conditional | ?? !! ff fff
R | Item assignment | = => \+= -= **= xx=
L | Loose unary | so not
X | Comma operator | , :
X | List infix | Z minmax X X~ X* Xeqv ...
R | List prefix | print push say die map substr ... [\+] [*] any Z=
X | Loose and | and andthen notandthen
X | Loose or | or xor orelse
X | Sequencer | <==, ==>, <<==, ==>>
N | Terminator | ; {...}, unless, extra ), ], }
=end table
Using two C<!> symbols below generically to represent any pair of operators
that have the same precedence, the associativities specified above
for binary operators are interpreted as follows:
=begin table
A | Assoc | Meaning of $a ! $b ! $c
===+=========+========================
L | left | ($a ! $b) ! $c
R | right | $a ! ($b ! $c)
N | non | ILLEGAL
C | chain | ($a ! $b) and ($b ! $c)
X | list | infix:<!>($a; $b; $c)
=end table
For unary operators this is interpreted as:
=begin table
A | Assoc | Meaning of !$a!
===+=========+==========================
L | left | (!$a)!
R | right | !($a!)
N | non | ILLEGAL
=end table
In the operator descriptions below, a default associativity of I<left>
is assumed.
=head1 Operator classification
X<|prefix operator>
X<|infix operator>
X<|postfix operator>
X<|circumfix operator>
X<|postcircumfix operator>
Operators can occur in several positions relative to a term:
=begin table
\+term | prefix
term1 \+ term2 | infix
term\+\+ | postfix
(term) | circumfix
term1[term2] | postcircumfix
=end table
Each operator is also available as a subroutine.
The name of the routine is formed from
the operator category, followed by a colon, then a list quote construct with the
symbol(s) that make up the operator:
infix:<+>(1, 2); # same as 1 + 2
circumfix:«[ ]»(<a b c>); # same as [<a b c>]
As a special case, a I<listop> (list operator) can stand either as a
term or as a prefix. Subroutine calls are the most common listops. Other
cases include meta-reduced infix operators (C<[+] 1, 2, 3>) and the
L<#prefix ...> etc. stub operators.
Defining custom operators is covered in
L<Defining Operators functions|/language/functions#Defining_Operators>.
=head1 Meta Operators
Meta operators can be parameterized with other operators or subroutines in the
same way as functions can take functions as parameters. To use a subroutine as
a parameter, prefix its name with a C<&>. Perl 6 will generate the actual
combined operator in the background, allowing the mechanism to be applied to
user defined operators. To disambiguate chained meta operators, enclose the
inner operator in square brackets. There are quite a few Meta operators with
different semantics as explained, next.
=head1 Substitution Operators
Each substitution operator comes into two main forms: a lowercase one (e.g., C<s///>) that
performs I<in-place> (i.e., I<destructive> behaviour;
and an uppercase form (e.g., C<S///>) that provides a I<non-destructive>
behavior.
=head2 X«C<s///> in-place substitution»
my $str = 'old string';
$str ~~ s/o .+ d/new/;
say $str; # OUTPUT: «new string»
C<s///> operates on the C<$_> topical variable, changing it in
place. It uses the given
L«C<Regex>|/type/Regex» to find portions to replace and changes them to the
provided replacement string. Sets C<$/> to the L«C<Match>|/type/Match» object
or, if multiple matches were made, a L«C<List>|/type/List» of C<Match> objects.
Returns C<$/>.
It's common to use this operator with the C<~~> smartmatch operator, as it
aliases left hand side to C<$_>, which C<s///> uses.
Regex captures can be referenced in the replacement part; it takes the same
adverbs as the L«C<.subst> method|/routine/subst», which go between the C<s>
and the opening C</>, separated with optional whitespace:
my $str = 'foo muCKed into the lEn';
# replace second 'o' with 'x'
$str ~~ s:2nd/o/x/;
# replace 'M' or 'L' followed by non-whitespace stuff with 'd'
# and lower-cased version of that stuff:
$str ~~ s :g :i/<[ML]> (\S+)/d{lc $0}/;
say $str; # OUTPUT: «fox ducked into the den»
You can also use a different delimiter:
my $str = 'foober';
$str ~~ s!foo!fox!;
$str ~~ s{b(.)r} = " d$0n";
say $str; # OUTPUT: «fox den»
Non-paired characters can simply replace the original slashes. Paired
characters, like braces, are used only on the match portion, with the
substitution given by assignment (of anything: a string, a routine call, etc.).
=head2 X«C<S///> non-destructive substitution»
say S/o .+ d/new/ with 'old string'; # OUTPUT: «new string»
S:g/« (.)/$0.uc()/.say for <foo bar ber>; # OUTPUT: «FooBarBer»
C<S///> uses the same semantics as the C<s///> operator, except
it leaves the original string intact
and I<returns the resultant string> instead of C<$/> (C<$/> still being set
to the same values as with C<s///>).
B<Note:> since the result is obtained as a return value, using this
operator with the C<~~> smartmatch operator is a mistake and will issue a
warning. To execute the substitution on a variable that isn't the C<$_> this
operator uses, alias it to C<$_> with C<given>, C<with>, or any other way.
Alternatively, use the L«C<.subst> method|/routine/subst».
=head2 X«C<tr///> in-place transliteration»
my $str = 'old string';
$str ~~ tr/dol/wne/;
say $str; # OUTPUT: «new string»
C<tr///> operates on the C<$_> topical variable and changes it in place.
It behaves similar to
L«C<Str.trans>|/routine/trans» called with a single L<Pair> argument, where
key is the matching part (characters C<dol> in the example above) and value is
the replacement part (characters C<wne> in the example above). Accepts the
same adverbs as L«C<Str.trans>|/routine/trans». Returns the StrDistance object
that measures the distance between original value and the resultant string.
my $str = 'old string';
$str ~~ tr:c:d/dol st//;
say $str; # OUTPUT: «ring»
=head2 X«C<TR///> non-destructive transliteration»
with 'old string' {
say TR/dol/wne/; # OUTPUT: «new string»
}
C<TR///> behaves the same as the C<tr///> operator,
except that it leaves the C<$_>
value untouched and instead returns the resultant string.
say TR:d/dol // with 'old string'; # OUTPUT: «string»
=head1 Assignment Operators
Infix operators can be combined with the assignment operator to modify a
value and apply the result to a container in one go. Containers will be
autovivified if possible. Some examples:
my $a = 32;
$a += 10; # 42
$a -= 2; # 40
$a = 3;
$a min= 5; # still 3
$a min= 2; # 2
my $s = 'a';
$s ~= 'b'; # 'ab'
This behavior is automatically extended to include custom-defined infix operators.
sub infix:<space-concat> ($a, $b) { $a ~ " " ~ $b };
my $a = 'word1';
$a space-concat= 'word2'; # RESULT: «'word1 word2'»
Although not strictly operators, methods can be used in the same fashion.
my Real $a = 1/2;
$a = 3.14;
$a .= round; # RESULT: «3»
=head1 Negated Relational Operators
X<|! (negation meta operator)>X<|!==>X<|!eq>
The result of a relational operator returning C<Bool> can be negated by
prefixing with C<!>. To avoid visual confusion with the C<!!> operator,
you may not modify any operator already beginning with C<!>.
There are shortcuts for C<!==> and C<!eq>, namely C<!=> and C<ne>.
my $a = True;
say so $a != True; # OUTPUT: «False»
my $i = 10;
my $release = Date.new(:2015year, :12month, :24day);
my $today = Date.today;
say so $release !before $today; # OUTPUT: «False»
=head1 Reversed Operators
X<|R,reverse meta operator>
Any infix operator may be called with its two arguments reversed by prefixing
with C<R>. Associativity of operands is reversed as well.
say 4 R/ 12; # OUTPUT: «3»
say [R/] 2, 4, 16; # OUTPUT: «2»
=head1 X<<<Hyper Operators|hyper,<<;hyper,>>;hyper,«;hyper,»>>>
Hyper Operators include C<«> and C<»>, with their ASCII variants C«<<»
and C«>>».
Hyper operators apply a given operator enclosed by C<«> and C<»> to one or two
lists, returning the resulting list. The pointy part of C<«> or C<»> has to
point to the shorter list. A list with just one element is fine too. If one of
the lists is shorter than the other, the operator will cycle over the shorter
list until all elements of the longer list are processed.
say (1, 2, 3) »*» 2; # OUTPUT: «(2 4 6)»
say (1, 2, 3, 4) »~» <a b>; # OUTPUT: «(1a 2b 3a 4b)»
say (1, 2, 3) »+« (4, 5, 6); # OUTPUT: «(5 7 9)»
Assignment meta operators can be hyped.
my @a = 1, 2, 3;
say @a »+=» 1; # OUTPUT: «[2 3 4]»
Hyper forms of unary operators have the pointy bit point to the operator and
the blunt end at the list to be operated on.
my @wisdom = True, False, True;
say !« @wisdom; # OUTPUT: «[False True False]»
my @a = 1, 2, 3;
@a»++; # OUTPUT: «(2, 3, 4)»
Hyper operators are defined recursively on nested arrays.
say -« [[1, 2], 3]; # OUTPUT: «[[-1 -2] -3]»
Also, methods can be called in an out of order, concurrent fashion. The resulting
list is in order. Note that all hyper operators are candidates for
autothreading and will cause tears if the methods have side effects. The
optimizer has full reign over hyper operators, which is the reason that they
cannot be defined by the user.
class CarefulClass { method take-care {} }
my CarefulClass @objs;
my @results = @objs».take-care();
my @slops; # May Contain Nuts
@slops».?this-method-may-not-exist();
Hyper operators can work with hashes. The pointy direction indicates if missing
keys are to be ignored in the resulting hash. The enclosed operator operates on
all values that have keys in both hashes.
=begin table
%foo «+» %bar; intersection of keys
%foo »+« %bar; union of keys
%outer »+» %inner; only keys of %inner that exist in %outer will occur in the result
=end table
my %outer = 1, 2, 3 Z=> <a b c>;
my %inner = 1, 2 Z=> <x z>;
say %outer «~» %inner; # OUTPUT: «{"1" => "ax", "2" => "bz"}»
Hyper operators can take user defined operators as their operator argument.
sub pretty-file-site (Int $size --> Str) {
# rounding version of infix:</>(Int, Int)
sub infix:<r/>(Int \i1, Int \i2) {
round(i1 / i2, 0.1)
}
# we build a vector of fractions of $size and zip that with the fitting prefix
for $size «[r/]« (2**60, 2**50, 2**40, 2**30, 2**20, 2**10)
Z <EB PB TB GB MB KB> -> [\v,\suffix] {
# starting with the biggest suffix, we take the first that is 0.5 of that suffix or bigger
return v ~ ' ' ~ suffix if v > 0.4
}
# this be smaller or equal then 0.4 KB
return $size.Str;
}
for 60, 50, 40, 30, 20, 10 -> $test {
my &a = { (2 ** $test) * (1/4, 1/2, 1, 10, 100).pick * (1..10).pick };
print pretty-file-site(a.Int) xx 2, ' ';
}
# OUTPUT: «10 EB 4 EB 2 PB 5 PB 0.5 PB 4 TB 300 GB 4.5 GB 50 MB 200 MB 9 KB 0.6 MB»
Whether hyperoperators descend into child lists depends on the
L<nodality|/language/typesystem#trait_is_nodal> of the inner operator of a
chain. For the hyper method call operator (».), the nodality of the target
method is significant.
say (<a b>, <c d e>)».elems; # OUTPUT: «(2 3)»
say (<a b>, <c d e>)».&{ .elems }; # OUTPUT: «((1 1) (1 1 1))»
You can chain hyper operators to destructure a List of Lists.
my $neighbors = ((-1, 0), (0, -1), (0, 1), (1, 0));
my $p = (2, 3);
say $neighbors »>>+<<» ($p, *); # OUTPUT: «((1 3) (2 2) (2 4) (3 3))»
=head1 Reduction Operators
X<|[] (reduction meta operators)>X<|[+] (reduction meta operators)>
The reduction metaoperator, C<[ ]>, reduces a list with the given infix
operator. It gives the same result as the L<reduce> routine - see there for
details.
# These two are equivalent:
say [+] 1, 2, 3; # OUTPUT: «6»
say reduce &infix:<+>, 1, 2, 3; # OUTPUT: «6»
No whitespace is allowed between the brackets and the operator. To wrap a
function instead of an operator, provide an additional layer of brackets:
sub plus { $^a + $^b };
say [[&plus]] 1, 2, 3; # OUTPUT: «6»
The argument list is iterated without flattening. This means that you can pass
a nested list to the reducing form of a list infix operator:
say [X~] (1, 2), <a b>; # OUTPUT: «1, 2 X~ <a b>»
By default, only the final result of the reduction is returned. Prefix the
wrapped operator with a C<\>, to return a lazy list of all intermediate values
instead. This is called a "triangular reduce".
If the non-meta part contains a C<\> already,
quote it with C<[]> (e.g. C<[\[\x]]>).
my @n = [\~] 1..*;
say @n[^5]; # OUTPUT: «(1 12 123 1234 12345)»
=head1 Cross Operators
X<|X (cross meta operator)>
The cross metaoperator, C<X>, will apply a given infix operator in order of
cross product to all lists, such that the rightmost operator varies most
quickly.
1..3 X~ <a b> # RESULT: «<1a, 1b, 2a, 2b, 3a, 3b>»
=head1 Zip Operators
X<|Z (zip meta operator)>
The zip metaoperator (which is not the same thing as L<Z|#infix_Z>) will
apply a given infix operator to pairs taken one left, one right, from its
arguments. The resulting list is returned.
my @l = <a b c> Z~ 1, 2, 3; # RESULT: «[a1 b2 c3]»
If one of the operands runs out of elements prematurely, the zip operator will
stop. An infinite list can be used to repeat elements. A list with a final
element of C<*> will repeat its 2nd last element indefinitely.
my @l = <a b c d> Z~ ':' xx *; # RESULT: «<a: b: c: d:>»
@l = <a b c d> Z~ 1, 2, *; # RESULT: «<a1 b2 c2 d2>»
If an infix operator is not given, C<,> (comma operator) will be used by default:
my @l = 1 Z 2; # RESULT: «[(1 2)]»
=head1 Sequential Operators
X<|S,sequential meta operator>
The sequential metaoperator, C<S>, will suppress any concurrency or reordering
done by the optimizer. Most simple infix operators are supported.
say so 1 S& 2 S& 3; # OUTPUT: «True»
=head1 Nesting of Meta Operators
To avoid ambiguity when chaining meta operators, use square brackets to help the
compiler understand you.
my @a = 1, 2, 3;
my @b = 5, 6, 7;
@a X[+=] @b;
say @a; # OUTPUT: «[19 20 21]»
=head1 Z<>Term Precedence
=head2 term C«< >»
The X<quote-words|qw;quote-words> construct breaks up the contents on whitespace and returns
a L<List|/type/List> of the words. If a word
looks like a number literal or a C<Pair> literal, it's converted to the
appropriate number.
say <a b c>[1]; # OUTPUT: «b»
=head2 term C«( )»
The X<grouping operator>.
An empty group C<()> creates an L<empty list|/type/List#index-entry-()_empty_list>.
Parentheses around non-empty expressions simply structure the expression, but do
not have additional semantics.
In an argument list, putting parenthesis around an argument prevents it from
being interpreted as a named argument.
multi sub p(:$a!) { say 'named' }
multi sub p($a) { say 'positional' }
p a => 1; # OUTPUT: «named»
p (a => 1); # OUTPUT: «positional»
=head2 term C«{ }»
L<Block> or L<Hash> constructor.X<|block constructor;hash constructor>
If the content is empty, or contains a single list that starts with a L<Pair> literal or
C<%>-sigiled variable, and the L«C<$_> variable|/syntax/$_» or placeholder parameters are
not used, the constructor returns a L<Hash>. Otherwise it constructs a L<Block>.
To force construction of a L<Block>, follow the opening brace with a semicolon.
To always ensure you end up with a L<Hash>, you can use C<%( )> coercer or L<hash> routine instead:
{}.^name.say; # OUTPUT: «Hash»
{;}.^name.say; # OUTPUT: «Block»
{:$_}.^name.say; # OUTPUT: «Block»
%(:$_).^name.say; # OUTPUT: «Hash»
hash(:$_).^name.say; # OUTPUT: «Hash»
=head2 circumfix C«[ ]»
The X<L<Array> constructor> returns an itemized L<Array> that does not flatten
in list context.
=head1 Method Postfix Precedence
=head2 postcircumfix C«[ ]»
=begin code :skip-test
sub postcircumfix:<[ ]>(@container, **@index,
:$k, :$v, :$kv, :$p, :$exists, :$delete)
=end code
Universal interface for positional access to zero or more elements of a
@container, a.k.a. "X<array indexing operator|array indexing operator;array subscript operator>".
my @alphabet = 'a' .. 'z';
say @alphabet[0]; # OUTPUT: «a»
say @alphabet[1]; # OUTPUT: «b»
say @alphabet[*-1]; # OUTPUT: «z»
say @alphabet[100]:exists; # OUTPUT: «False»
say @alphabet[15, 4, 17, 11].join; # OUTPUT: «perl»
say @alphabet[23 .. *].perl; # OUTPUT: «("x", "y", "z")»
@alphabet[1, 2] = "B", "C";
say @alphabet[0..3].perl # OUTPUT: «("a", "B", "C", "d")»
See L<Subscripts|/language/subscripts>, for a more detailed explanation of this
operator's behavior and for how to implement support for it in custom types.
=head2 postcircumfix C«{ }»
=begin code :skip-test
sub postcircumfix:<{ }>(%container, **@key,
:$k, :$v, :$kv, :$p, :$exists, :$delete)
=end code
Universal interface for associative access to zero or more elements of a
%container, a.k.a. "X<hash indexing operator|hash indexing operator;hash subscript operator>".
my %color = kiwi => "green", banana => "yellow", cherry => "red";
say %color{"banana"}; # OUTPUT: «yellow»
say %color{"cherry", "kiwi"}.perl; # OUTPUT: «("red", "green")»
say %color{"strawberry"}:exists; # OUTPUT: «False»
%color{"banana", "lime"} = "yellowish", "green";
%color{"cherry"}:delete;
say %color; # OUTPUT: «banana => yellowish, kiwi => green, lime => green»
See L«C«postcircumfix < >»|/routine/< >#(Operators)_postcircumfix_<_>» and
L<C<postcircumfix « »>|/routine/« »#(Operators)_postcircumfix_«_»> for convenient
shortcuts, and L<Subscripts|/language/subscripts> for a more detailed
explanation of this operator's behavior and how to implement support for it
in custom types.
=head2 postcircumfix C«< >»
Shortcut for L<C<postcircumfix { }>|/routine/{ }#(Operators)_postcircumfix_{_}> that quotes
its argument using the same rules as the L«quote-words operator|
/routine/< >#circumfix_<_>» of the same name.
my %color = kiwi => "green", banana => "yellow", cherry => "red";
say %color<banana>; # OUTPUT: «yellow»
say %color<cherry kiwi>.perl; # OUTPUT: «("red", "green")»
say %color<strawberry>:exists; # OUTPUT: «False»
Technically, not a real operator; it's syntactic sugar that's turned into the
C<{ }> postcircumfix operator at compile-time.
=head2 postcircumfix C<« »>
Shortcut for L<C<postcircumfix { }>|/routine/{ }#(Operators)_postcircumfix_{_}> that quotes
its argument using the same rules as the L<interpolating quote-words operator|
/routine/« »#circumfix_«_»> of the same name.
my %color = kiwi => "green", banana => "yellow", cherry => "red";
my $fruit = "kiwi";
say %color«cherry "$fruit"».perl; # OUTPUT: «("red", "green")»
Technically, not a real operator; it's syntactic sugar that's turned into the
C<{ }> postcircumfix operator at compile-time.
=head2 postcircumfix C«( )»
The X<call operator> treats the invocant as a L<Callable> and invokes it,
using the expression between the parentheses as arguments.
Note that an identifier followed by a pair of parentheses is always parsed as a
subroutine call.
If you want your objects to respond to the call operator,
implement a C<method CALL-ME>.
=head2 postfix C«.»
The operator for calling one method, C<$invocant.method>.X<|method call>
Technically, not a real operator; it's syntax special-cased in the compiler.
X«|postfix .&»
=head2 postfix C«.&»
The operator to call a subroutine (with at least one positional argument), such
as a method. The invocant will be bound to the first positional argument.
Technically, not a real operator; it's syntax special-cased in the compiler.
my sub f($invocant){ "The arg has a value of $invocant" }
42.&f;
# OUTPUT: «The arg has a value of 42»
42.&(-> $invocant { "The arg has a value of $invocant" });
# OUTPUT: «The arg has a value of 42»
=head2 postfix C«.=»
A X<mutating method call>. C<$invocant.=method> desugars to
C<$invocant = $invocant.method>, similar to L<C<=>>.
Technically, not a real operator; it's syntax special-cased in the compiler.
X«|postfix .^»
=head2 postfix C«.^»
A X<meta-method call>. C<$invocant.^method> calls C<method> on C<$invocant>'s
metaclass. It desugars to C<$invocant.HOW.method($invocant, ...)>. See
L<HOW|/language/mop#index-entry-syntax_HOW-HOW> for more information.
Technically, not a real operator; it's syntax special-cased in the compiler.
X«|postfix .?»
=head2 postfix C«.?»
X<Safe call operator>. C<$invocant.?method> calls method C<method> on
C<$invocant> if it has a method of such name. Otherwise it returns L<Nil>.
Technically, not a real operator; it's syntax special-cased in the compiler.
X«|postfix .+»
=head2 postfix C«.+»
C<$foo.+meth> walks the MRO and calls all the methods called C<meth> and submethods called C<meth> if the type is the same as type of C<$foo>.
Those methods might be multis, in which case the matching candidate
would be called.
After that, a L<List> of the results are returned. If no such method was found,
it throws a L<X::Method::NotFound> exception.
class A {
method foo { say "from A"; }
}
class B is A {
multi method foo { say "from B"; }
multi method foo(Str) { say "from B (Str)"; }
}
class C is B is A {
multi method foo { say "from C"; }
multi method foo(Str) { say "from C (Str)"; }
}
say C.+foo; # OUTPUT: «from Cfrom Bfrom A(True True True)»
X«|postfix .*»
=head2 postfix C«.*»
C<$foo.*meth> walks the MRO and calls all the methods called C<meth> and submethods called C<meth> if the type is the same as type of C<$foo>.
Those methods might be multis, in which case the matching candidate
would be called.
After that, a L<List> of the results are returned. If no such method was found,
an empty L<List> is returned.
Technically, postfix C<.+> calls C<.*> at first. Read postfix C<.+> section to
see examples.
X<|postfix ».>X«|postfix >>.»
=head2 postfix C<».> / postfix C«>>.»
X<Hyper method call operator>. Will call a method on all elements of a C<List> out of order and return the list of return values in order.
my @a = <a b c>;
my @b = @a».ord; # OUTPUT: «[97, 98, 99]»
sub foo(Str:D $c){ $c.ord * 2 }; # The first parameter of a method is the invocant.
say @a».&foo; # So we can pretend to have a method call with a sub that got a good first positional argument.
say @a».&{ .ord}; # Blocks have an implicit positional arguments that lands in $_. The latter can be omitted for method calls.
Take care to avoid a
L<common mistake|/language/traps#Using_»_and_map_interchangeably> of expecting
side-effects to occur in order. The following C<say> is B<not>
guaranteed to produce the output in order:
=begin code :skip-test
@a».say; # WRONG! Could produce abc or cba or any other order
=end code
=head2 postfix C<.postfix> / C<.postcircumfix>
X<|.( )>X<|.[ ]>X<|.{ }>
In most cases, a dot may be placed before a postfix or postcircumfix:
my @a;
@a[1, 2, 3];
@a.[1, 2, 3]; # Same
This can be useful for visual clarity or brevity. For example, if an object's
attribute is a function, putting a pair of parentheses after the attribute name
will become part of the method call. So, either two pairs of parentheses must be
used or a dot has to come before the parentheses to separate it from the method
call.
class Operation {
has $.symbol;
has &.function;
}
my $addition = Operation.new(:symbol<+>, :function{ $^a + $^b });
say $addition.function()(1, 2); # OUTPUT: «3»
# OR
say $addition.function.(1, 2); # OUTPUT: «3»
If the postfix is an identifier, however, it will be interpreted as a normal
method call.
=begin code
1.i # No such method 'i' for invocant of type 'Int'
=end code
Technically, not a real operator; it's syntax special-cased in the compiler.
X<|postfix call>
=head2 postfix C«.:<prefix>»
A prefix can be called like a method using colonpair notation. For example:
my $a = 1;
say ++$a; # OUTPUT: «2»
say $a.:<++>; # OUTPUT: «3»
Technically, not a real operator; it's syntax special-cased in the compiler.
X<|prefix call>
=head2 postfix C«.::»
A X<class-qualified method call>, used to call a method as defined in a parent
class or role, even after it has been redefined in the child class.
class Bar {
method baz { 42 }
}
class Foo is Bar {
method baz { "nope" }
}
say Foo.Bar::baz; # OUTPUT: «42»
=head1 Autoincrement Precedence
=head2 prefix X<C«++»|++>
multi sub prefix:<++>($x is rw) is assoc<non>
Increments its argument by one and returns the updated value.X<|prefix increment operator>
my $x = 3;
say ++$x; # OUTPUT: «4»
say $x; # OUTPUT: «4»
It works by calling the L<succ> method (for I<successor>) on its argument,
which gives custom types the freedom to implement their own increment
semantics.
=head2 prefix X<C«--»|-->
multi sub prefix:<-->($x is rw) is assoc<non>
Decrements its argument by one and returns the updated value.X<|decrement operator>
my $x = 3;
say --$x; # OUTPUT: «2»
say $x; # OUTPUT: «2»
It works by calling the L<pred> method (for I<predecessor>) on its argument,
which gives custom types the freedom to implement their own decrement
semantics.
=head2 postfix X<C«++»|++>
multi sub postfix:<++>($x is rw) is assoc<non>
Increments its argument by one and returns the original value.X<|postfix increment operator>
my $x = 3;
say $x++; # OUTPUT: «3»
say $x; # OUTPUT: «4»
It works by calling the L<succ> method (for I<successor>) on its argument,
which gives custom types the freedom to implement their own increment
semantics.
Note that this does not necessarily return its argument; e.g., for
undefined values, it returns 0:
my $x;
say $x++; # OUTPUT: «0»
say $x; # OUTPUT: «1»
Increment on L<Str|/type/Str> will increment the number part of a string and
assign the resulting string to the container. A C<is rw>-container is required.
my $filename = "somefile-001.txt";
say $filename++ for 1..3;
# OUTPUT: «somefile-001.txtsomefile-002.txtsomefile-003.txt»
=head2 postfix C«--»
multi sub postfix:<-->($x is rw) is assoc<non>
Decrements its argument by one and returns the original value.X<|decrement operator>
my $x = 3;
say $x--; # OUTPUT: «3»
say $x; # OUTPUT: «2»
It works by calling the L<pred> method (for I<predecessor>) on its argument,
which gives custom types the freedom to implement their own decrement
semantics.
Note that this does not necessarily return its argument;e.g., for
undefined values, it returns 0:
my $x;
say $x--; # OUTPUT: «0»
say $x; # OUTPUT: «-1»
Decrement on L<Str|/type/Str> will decrement the number part of a string and
assign the resulting string to the container. A C<is rw>-container is required.
Crossing 0 is prohibited and throws C<X::AdHoc>.
my $filename = "somefile-003.txt";
say $filename-- for 1..3;
# OUTPUT: «somefile-003.txtsomefile-002.txtsomefile-001.txt»
=head1 Exponentiation Precedence
=head2 infix C«**»
multi sub infix:<**>(Any, Any --> Numeric:D) is assoc<right>
The X<exponentiation operator> coerces both arguments to L<Numeric>
and calculates the left-hand-side raised to the power of the right-hand side.
If the right-hand side is a non-negative integer and the left-hand side
is an arbitrary precision type (L<Int>, L<FatRat>), then the calculation
is carried out without loss of precision.
=head1 Symbolic Unary Precedence
=head2 prefix C«?»
multi sub prefix:<?>(Mu --> Bool:D)
X<Boolean context operator>.
Coerces the argument to L<Bool> by calling the C<Bool> method on it.
Note that this collapses L<Junction>s.
=head2 prefix C«!»
multi sub prefix:<!>(Mu --> Bool:D)
X<Negated boolean context operator>.
Coerces the argument to L<Bool> by calling the C<Bool> method on it,
and returns the negation of the result.
Note that this collapses L<Junction>s.
=head2 prefix C«+»
multi sub prefix:<+>(Any --> Numeric:D)
X<Numeric context operator>.
Coerces the argument to L<Numeric> by calling the C<Numeric> method on it.
=head2 prefix C«-»
multi sub prefix:<->(Any --> Numeric:D)
X<Negative numeric context operator>.
Coerces the argument to L<Numeric> by calling the C<Numeric> method on it,
and then negates the result.
=head2 prefix C«~»
multi sub prefix:<~>(Any --> Str:D)
X<String context operator>.
Coerces the argument to L<Str> by calling the L<Str|/type/List#method_Str> method on it.
=head2 prefix C«|»
Flattens objects of type L<Capture>, L<Pair>, L<List>, L<Map> and L<Hash>
into an argument list.
Outside of argument lists, it returns a L<Slip|/type/Slip>, which makes it
flatten into the outer list. Inside L<argument list|/language/list#Argument_List_(Capture)_Context> L<C<Positional>s|/type/Positional> are turned
into positional arguments and L<C<Associative>s|/type/Associative> are turned into named arguments.
=head2 prefix C«||»
TODO
=head2 prefix C«+^»
multi sub prefix:<+^>(Any --> Int:D)
X<Integer bitwise negation operator>.
Coerces the argument to L<Int> and does a bitwise negation on the result,
assuming L<two's complement|https://en.wikipedia.org/wiki/Two%27s_complement>.
=head2 prefix C«~^»
Coerces the argument to a non-variable-encoding string buffer type (e.g. C<buf8>, C<buf16>, C<buf32>)
and then flips each bit in that buffer.
Please note that this has not yet been implemented.
=head2 prefix C«?^»
multi sub prefix:<?^>(Mu --> Bool:D)
X<Boolean bitwise negation operator>.
Coerces the argument to L<Bool> and then does a bit flip, which makes it the
same as C<< prefix:<!> >>.
=head2 prefix C«^»
multi sub prefix:<^>(Any --> Range:D)
I<upto> operator.X<|upto operator>
Coerces the argument to L<Numeric>, and generates a range from 0 up to (but
excluding) the argument.
say ^5; # OUTPUT: «0..^5»
for ^5 { } # 5 iterations
=head1 Dotty Infix Precedence
These operators are like their Method Postfix counterparts, but require
surrounding whitespace (before and/or after) to distinguish them.
=head2 infix C«.=»
Calls the right-side method on the value in the left-side container,
replacing the resulting value in the left-side container.
In most cases, this behaves identically to the postfix mutator, but the
precedence is lower:
=for code :skip-test
my $a = -5
say ++$a.=abs
# OUTPUT: «6»
say ++$a .= abs
# OUTPUT: «Cannot modify an immutable Int
# in block <unit> at <tmp> line 1»
=head2 infix C«.»
Calls the following method (whose name must be alphabetic) on the left-side
invocant.
Note that the infix form of the operator has a slightly lower precedence
than postfix C<.meth>.
say -5.abs; # like: -(5.abs)
# OUTPUT: «-5»
say -5 . abs; # like: (-5) . abs
# OUTPUT: «5»
say -5 .abs; # following whitespace is optional
# OUTPUT: «5»
=head1 Multiplicative Precedence
=head2 infix C«*»
multi sub infix:<*>(Any, Any --> Numeric:D)
X<Multiplication operator>.
Coerces both arguments to L<Numeric> and multiplies them. The result
is of the wider type. See L<Numeric> for details.