/
traps.pod6
1893 lines (1405 loc) · 63.6 KB
/
traps.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<index> :page-order<a62>
=TITLE Traps to avoid
=SUBTITLE Traps to avoid when getting started with Perl 6
When learning a programming language, possibly with the background of
being familiar with another programming language, there are always some
things that can surprise you and might cost valuable time in debugging
and discovery.
This document aims to show common misconceptions in order to avoid them.
During the making of Perl 6 great pains were taken to get rid of warts in
the syntax. When you whack one wart, though, sometimes another pops up. So
a lot of time was spent finding the minimum number of warts or trying to put
them where they would rarely be seen. Because of this, Perl 6's warts are
in different places than you may expect them to be when coming from another
language.
=head1 Variables and Constants
=head2 Constants are Computed at Compile Time
Constants are computed at compile time, so if you use them in modules keep in mind
that their values will be frozen due to pre-compilation of the module itself:
=for code :skip-test
# WRONG (most likely):
unit module Something::Or::Other;
constant $config-file = "config.txt".IO.slurp;
The C<$config-file> will be slurped during pre-compilation and changes to
C<config.txt> file won't be re-loaded when you start the script again; only when
the module is re-compiled.
Avoid L<using a container|/language/containers> and prefer
L<binding a value|/language/containers#Binding> to a variable that offers
a behaviour similar to a constant, but allowing the value to get updated:
=for code :skip-test
# Good; file gets updated from 'config.txt' file on each script run:
unit module Something::Or::Other;
my $config-file := "config.txt".IO.slurp;
=head2 Assigning to C<Nil> produces a different value, usually C<Any>.
Actually, assigning to C<Nil> L<reverts the variable to its default value|https://docs.perl6.org/type/Nil>. So:
=begin code
my @a = 4, 8, 15, 16;
@a[2] = Nil;
say @a; # OUTPUT: «[4 8 (Any) 16]»
=end code
In this case, C<Any> is the default value of an C<Array> element.
You can purposefully assign C<Nil> as a default value:
=begin code
my %h is default(Nil) = a => Nil;
say %h; # OUTPUT: «Hash %h = {:a(Nil)}»
=end code
Or bind a value to C<Nil> if that is the result you want:
=begin code :preamble<my @a = 1,2,3,4;>
@a[3] := Nil;
say @a; # OUTPUT: «[4 8 (Any) Nil]»
=end code
This trap might be hidden in the result of functions, such as matches:
=begin code
my $result2 = 'abcdef' ~~ / dex /;
say "Result2 is { $result2.^name }"; # OUTPUT: «Result2 is Any»
=end code
A L<C<Match> will be C<Nil>|https://docs.perl6.org/language/regexes#Literals> if it finds nothing; however it assigning C<Nil> to C<$result2> above will result in its default value, which is C<Any> as shown.
=head2 Using a block to interpolate anon state vars
The programmer intended for the code to count the number of times the routine
is called, but the counter is not increasing:
=begin code
sub count-it { say "Count is {$++}" }
count-it;
count-it;
# OUTPUT:
# Count is 0
# Count is 0
=end code
When it comes to state variables, the block in which the vars are
declared gets cloned — and vars get initialized anew—whenever that
block's block is re-entered. This lets constructs like the one below
behave appropriately: the state variable inside the loop gets
initialized anew each time the sub is called:
=begin code
sub count-it {
for ^3 {
state $count = 0;
say "Count is $count";
$count++;
}
}
count-it;
say "…and again…";
count-it;
# OUTPUT:
# Count is 0
# Count is 1
# Count is 2
# …and again…
# Count is 0
# Count is 1
# Count is 2
=end code
The same layout exists in our buggy program. The C<{ }> inside a
double-quoted string isn't merely an interpolation to execute a piece of
code. It's actually its own block, which is just as in the example above
gets cloned each time the sub is entered, re-initializing our state
variable. To get the right count, we need to get rid of that inner
block, using a scalar contextualizer to interpolate our piece of code
instead:
=begin code
sub count-it { say "Count is $($++)" }
count-it;
count-it;
# OUTPUT:
# Count is 0
# Count is 1
=end code
Alternatively, you can also use the L<concatenation operator|/routine/~> instead:
=begin code
sub count-it { say "Count is " ~ $++ }
=end code
=head1 Blocks
=head2 Beware of empty "blocks"
Curly braces are used to declare blocks. However, empty curly braces will
declare a hash.
=begin code
$ = {say 42;} # Block
$ = {;} # Block
$ = {…} # Block
$ = { } # Hash
=end code
You can use the second form if you effectively want to declare an empty block:
my &does-nothing = {;};
say does-nothing(33);# OUTPUT: «Nil»
=head1 Objects
=head2 Assigning to attributes
Newcomers often think that, because attributes with accessors are declared
as C<has $.x>, they can assign to C<$.x> inside the class. That's not the
case.
For example
=begin code
use v6.c;
class Point {
has $.x;
has $.y;
method double {
$.x *= 2; # WRONG
$.y *= 2; # WRONG
self;
}
}
say Point.new(x => 1, y => -2).double.x
# OUTPUT: «Cannot assign to an immutable value»
=end code
in the first line marked with C<# WRONG>, because C<$.x>, short for C<$(
self.x )>, is a call to a read-only accessor.
The syntax C<has $.x> is short for something like C<has $!x; method x() {
$!x }>, so the actual attribute is called C<$!x>, and a read-only accessor
method is automatically generated.
Thus the correct way to write the method C<double> is
=for code :skip-test
method double {
$!x *= 2;
$!y *= 2;
self;
}
which operates on the attributes directly.
=head2 C<BUILD> prevents automatic attribute initialization from constructor arguments
When you define your own C<BUILD> submethod, you must take care of
initializing all attributes by yourself. For example
=begin code
use v6.c;
class A {
has $.x;
has $.y;
submethod BUILD {
$!y = 18;
}
}
say A.new(x => 42).x; # OUTPUT: «Any»
=end code
leaves C<$!x> uninitialized, because the custom C<BUILD> doesn't initialize
it.
B<Note:> Consider using L<TWEAK|/language/objects#index-entry-TWEAK>
instead. L<Rakudo|/language/glossary#Rakudo> supports L<TWEAK|/language/objects#index-entry-TWEAK> method
since release 2016.11.
One possible remedy is to explicitly initialize the attribute in C<BUILD>:
=for code :skip-test
submethod BUILD(:$x) {
$!y = 18;
$!x := $x;
}
which can be shortened to:
=for code :skip-test
submethod BUILD(:$!x) {
$!y = 18;
}
Another, more general approach is to leave C<BUILD> alone, and hook into the
C<BUILDALL> mechanism instead:
=begin code
use v6.c;
class A {
has $.x;
has $.y;
method BUILDALL(|c) {
callsame;
$!y = 18;
self
}
}
say A.new(x => 42).x; # OUTPUT: «42»
=end code
Remember that C<BUILDALL> is a method, not a submethod. That's because by
default, there is only one such method per class hierarchy, whereas C<BUILD>
is explicitly called per class. That is the reason why, in order to properly initialize
parent objects, it is required to use C<callsame> inside C<BUILDALL>, but not inside C<BUILD>
(for more on the subject see L<object creation|/language/objects#Object_Construction>).
=head1 Whitespace
=head2 Whitespace in Regexes does not match literally
=for code
say 'a b' ~~ /a b/; # OUTPUT: «False»
Whitespace in regexes is, by default, considered an optional filler without
semantics, just like in the rest of the Perl 6 language.
Ways to match whitespace:
=item C<\s> to match any one whitespace, C<\s+> to match at least one
=item C<' '> (a blank in quotes) to match a single blank
=item C<\t>, C<\n> for specific whitespace (tab, newline)
=item C<\h>, C<\v> for horizontal, vertical whitespace
=item C<<.ws>>, a built-in rule for whitespace that oftentimes does what
you actually want it to do
=item with C<m:s/a b/> or C<m:sigspace/a b/>, the blank in the regexes
matches arbitrary whitespace
=head2 Ambiguities in Parsing
While some languages will let you get away with removing as much whitespace
between tokens as possible, Perl 6 is less forgiving. The overarching
mantra is we discourage code golf, so don't scrimp on whitespace (the
more serious underlying reason behind these restrictions is
single-pass parsing and ability to parse Perl 6 programs with virtually
no L<backtracking|https://en.wikipedia.org/wiki/Backtracking>).
The common areas you should watch out for are:
=head3 Block vs. Hash slice ambiguity
=for code :skip-test
# WRONG; trying to hash-slice a Bool:
while ($++ > 5){ .say }
=begin code
# RIGHT:
while ($++ > 5) { .say }
# EVEN BETTER; Perl 6 does not require parentheses there:
while $++ > 5 { .say }
=end code
=head3 Reduction vs. Array constructor ambiguity
=for code :skip-test
# WRONG; ambiguity with `[<]` meta op:
my @a = [[<foo>],];
=begin code
# RIGHT; reductions cannot have spaces in them, so put one in:
my @a = [[ <foo>],];
# No ambiguity here, natural spaces between items suffice to resolve it:
my @a = [[<foo bar ber>],];
=end code
=head3 Less than vs. Word quoting/Associative indexing
=for code :skip-test
# WRONG; trying to index 3 associatively
say 3<5>4
=begin code
# RIGHT; prefer some extra whitespace around infix operators
say 3 < 5 > 4
=end code
=head1 Captures
=head2 Containers versus values in a Capture
Beginners might expect a variable in a C<Capture> to supply its current
value when that C<Capture> is later used. For example:
=for code
my $a = 2; say join ",", ($a, ++$a); # OUTPUT: «3,3»
Here the C<Capture> contained the B<container> pointed to by C<$a> and the
B<value> of the result of the expression C<++$a>. Since the C<Capture> must
be reified before C<&say> can use it, the C<++$a> may happen before C<&say>
looks inside the container in C<$a> (and before the C<List> is created with the two terms) and so it may already be incremented.
Instead, use an expression that produces a value when you want a value.
=for code
my $a = 2; say join ",", (+$a, ++$a); # OUTPUT: «2,3»
Or even simpler
=for code
my $a = 2; say "$a, {++$a}"; # OUTPUT: «2, 3»
The same happens in this case:
=begin code
my @arr;
my ($a, $b) = (1,1);
for ^5 {
($a,$b) = ($b, $a+$b);
@arr.push: ($a, $b);
say @arr
};
=end code
Outputs C<«[(1 2)][(2 3) (2 3)][(3 5) (3 5) (3 5)]...>. C<$a> and C<$b> are not reified until C<say> is called, the value that they have in that precise moment is the one printed. To avoid that, decontainerize values or take them out of the variable in some way before using them.
=begin code
my @arr;
my ($a, $b) = (1,1);
for ^5 {
($a,$b) = ($b, $a+$b);
@arr.push: ($a.item, $b.item);
say @arr
};
=end code
With L<item|/routine/item>, the container will be evaluated in item context, its
value extracted, and the desired outcome achieved.
=head1 C<Cool> tricks
Perl 6 includes a L<Cool|/type/Cool> class, which provides some of the DWIM
behaviors we got used to by coercing arguments when necessary. However, DWIM is
never perfect. Especially with L<List>s, which are C<Cool>, there are many
methods that will not do what you probably think they do, including C<contains>,
C<starts-with> or C<index>. Please see some examples in the section below.
=head2 Strings are not C<List>s, so beware indexing
In Perl 6, L<strings|/type/Str> are not lists of characters. One
L<cannot iterate|#Strings_are_not_iterable> over them or index into them as you can
with L<lists|/type/List>, despite the name of the L<.index routine|/type/Str#routine_index>.
=head2 C<List>s become strings, so beware C<.index()>ing
L<List|/type/List> inherits from L<Cool|/type/Cool>, which provides access to
L<.index|/type/Str#routine_index>. Because of the way C<.index>
L<coerces|/type/List#method_Str> a C<List> into a L<Str|/type/Str>, this can
sometimes appear to be returning the index of an element in the list, but
that is not how the behavior is defined.
=for code
my @a = <a b c d>;
say @a.index(‘a’); # 0
say @a.index('c'); # 4 -- not 2!
say @a.index('b c'); # 2 -- not undefined!
say @a.index(<a b>); # 0 -- not undefined!
These same caveats apply to L<.rindex|/type/Str#routine_rindex>.
=head2 C<List>s become strings, so beware C<.contains()>
Similarly, L<.contains|/type/List#(Cool)_method_contains> does not look for
elements in the list.
=for code
my @menu = <hamburger fries milkshake>;
say @menu.contains('hamburger'); # True
say @menu.contains('hot dog'); # False
say @menu.contains('milk'); # True!
say @menu.contains('er fr'); # True!
say @menu.contains(<es mi>); # True!
If you actually want to check for the presence of an element, use the
L<(cont)|/routine/(cont)> operator for single elements, and the
L<superset|/routine/(%3E%3D)> and L<strict superset|/routine/(%3E)>
operators for multiple elements.
=for code
my @menu = <hamburger fries milkshake>;
say @menu (cont) 'fries'; # True
say @menu (cont) 'milk'; # False
say @menu (>) <hamburger fries>; # True
say @menu (>) <milkshake fries>; # True (! NB: order doesn't matter)
If you are doing a lot of element testing, you may be better off using
a L<Set|/type/Set>.
=head2 C<Numeric> literals are parsed before coercion
Experienced programmers will probably not be surprised by this, but
Numeric literals will be parsed into their numeric value before being
coerced into a string, which may create nonintuitive results.
=for code
say 0xff.contains(55); # True
say 0xff.contains(0xf); # False
say 12_345.contains("23"); # True
say 12_345.contains("2_"); # False
=head2 Getting a random item from a C<List>
A common task is to retrieve one or more random elements from a collection,
but C<List.rand> isn't the way to do that. L<Cool|/type/Cool> provides
L<rand|/routine/rand#class_Cool>, but that first coerces the C<List> into
the number of items in the list, and returns a random real number
between 0 and that value. To get random elements, see L<pick|/routine/pick>
and L<roll|/routine/roll>.
=for code
my @colors = <red orange yellow green blue indigo violet>;
say @colors.rand; # 2.21921955680514
say @colors.pick; # orange
say @colors.roll; # blue
say @colors.pick(2); # yellow violet (cannot repeat)
say @colors.roll(3); # red green red (can repeat)
=head2 List numify to their number of elements in numeric context
You want to check whether a number is divisible by any of a set of numbers:
say 42 %% <11 33 88 55 111 20325>; # OUTPUT: «True
What? There's no single number 42 should be divisible by. However, that list has 6 elements, and 42 is divisible by 6. That's why the output is true. In this case, you should turn the C<List> into a L<Junction>:
say 42 %% <11 33 88 55 111 20325>.any;# OUTPUT: «any(False, False, False, False, False, False)»
which will clearly reveal the falsehood of the divisiveness of all the numbers in the list, which will be numified separately.
=head1 Arrays
=head2 Referencing the last element of an array
In some languages one could reference the last element of an array by
asking for the "-1th" element of the array, e.g.:
=for code :lang<perl5>
my @array = qw{victor alice bob charlie eve};
say @array[-1]; # OUTPUT: «eve»
In Perl 6 it is not possible to use negative subscripts, however the same is
achieved by actually using a function, namely C<*-1>. Thus accessing the
last element of an array becomes:
=for code
my @array = qw{victor alice bob charlie eve};
say @array[*-1]; # OUTPUT: «eve»
Yet another way is to utilize the array's tail method:
=for code
my @array = qw{victor alice bob charlie eve};
say @array.tail; # OUTPUT: «eve»
say @array.tail(2); # OUTPUT: «(charlie eve)»
=head2 Typed Array parameters
Quite often new users will happen to write something like:
=for code
sub foo(Array @a) { ... }
...before they have gotten far enough in the documentation to realize that
this is asking for an Array of Arrays. To say that C<@a> should only accept
Arrays, use instead:
=for code
sub foo(@a where Array) { ... }
It is also common to expect this to work, when it does not:
=for code
sub bar(Int @a) { 42.say };
bar([1, 2, 3]); # expected Positional[Int] but got Array
The problem here is that [1, 2, 3] is not an C<Array[Int]>, it is a plain
old Array that just happens to have Ints in it. To get it to work,
the argument must also be an C<Array[Int]>.
=for code :skip-test
my Int @b = 1, 2, 3;
bar(@b); # OUTPUT: «42»
bar(Array[Int].new(1, 2, 3));
This may seem inconvenient, but on the upside it moves the type-check
on what is assigned to C<@b> to where the assignment happens, rather
than requiring every element to be checked on every call.
=head2 Using C<«»> quoting when you don't need it
This trap can be seen in different varieties. Here are some of them:
=begin code
my $x = ‘hello’;
my $y = ‘foo bar’;
my %h = $x => 42, $y => 99;
say %h«$x»; # ← WRONG; assumption that $x has no whitespace
say %h«$y»; # ← WRONG; splits ‘foo bar’ by whitespace
say %h«"$y"»; # ← KINDA OK; it works but there is no good reason to do that
say %h{$y}; # ← RIGHT; this is what should be used
run «touch $x»; # ← WRONG; assumption that only one file will be created
run «touch $y»; # ← WRONG; will touch file ‘foo’ and ‘bar’
run «touch "$y"»; # ← WRONG; better, but has a different issue if $y starts with -
run «touch -- "$y"»; # ← KINDA OK; it works but there is no good enough reason to do that
run ‘touch’, ‘--’, $y; # ← RIGHT; explicit and *always* correct
run <touch -->, $y; # ← RIGHT; < > are OK, this is short and correct
=end code
Basically, C<«»> quoting is only safe to use if you remember to
I<always> quote your variables. The problem is that it inverts the
default behavior to unsafe variant, so just by forgetting some quotes
you are risking to introduce either a bug or maybe even a security
hole. To stay on the safe side, refrain from using C<«»>.
=head1 Strings
=head2 Quotes and interpolation
Interpolation in string literals can be too clever for your own good.
=for code :skip-test
"$foo<html></html>" # Perl 6 understands that as:
"$foo{'html'}{'/html'}"
=for code :skip-test
"$foo(" ~ @args ~ ")" # Perl 6 understands that as:
"$foo(' ~ @args ~ ')"
You can avoid those problems using non-interpolating single quotes and switching
to more liberal interpolation with C<\qq[]> escape sequence:
=for code
my $a = 1;
say '\qq[$a]()$b()';
# OUTPUT: «1()$b()»
Another alternative is to use C<Q:c> quoter, and use code blocks C<{}> for
all interpolation:
=for code
my $a = 1;
say Q:c«{$a}()$b()»;
# OUTPUT: «1()$b()»
=head2 Strings are not iterable
There are methods that L<Str|/type/Str> inherits from L<Any|/type/Any> that work on iterables like lists. Iterators on strings contain one element that is the whole string. To use list-based methods like C<sort>, C<reverse>, you need to convert the string into a list first.
=for code
say "cba".sort; # OUTPUT: «(cba)»
say "cba".comb.sort.join; # OUTPUT: «abc»
=head2 C<.chars> Gets the Number of Graphemes, not Codepoints
In Perl 6, L«C<.chars>|chars» returns the number of graphemes, or user visible characters.
These graphemes could be made up of a letter plus an accent for example.
If you need the number of codepoints, you should use L«C<.codes>|codes». If you need
the number of bytes when encoded as UTF8, you should use C<.encode.bytes> to
encode the string as UTF8 and then get the number of bytes.
say "\c[LATIN SMALL LETTER J WITH CARON, COMBINING DOT BELOW]"; # OUTPUT: «ǰ̣»
say 'ǰ̣'.codes; # OUTPUT: «2»
say 'ǰ̣'.chars; # OUTPUT: «1»
say 'ǰ̣'.encode.bytes; # OUTPUT: «4»
For more information on how strings work in Perl 6, see the L<Unicode page|/language/unicode>.
=head2 All Text is Normalized By Default
Perl 6 normalizes all text into Unicode NFC form (Normalization Form Canonical).
Filenames are the only text not normalized by default. If you are expecting
your strings to maintain a byte for byte representation as the original,
you need to use L«C<UTF8-C8>|/language/unicode#UTF8-C8» when reading or writing
to any filehandles.
=head2 Allomorphs Generally Follow Numeric Semantics
L<Str> C<"0"> is C<True>, while L<Numeric> is C<False>. So what's the L<Bool> value of
L<allomorph|/language/glossary#index-entry-Allomorph> C«<0>»?
In general, allomorphs follow L<Numeric> semantics, so the ones that I<numerically> evaluate
to zero are C<False>:
say so <0>; # OUTPUT: «False»
say so <0e0>; # OUTPUT: «False»
say so <0.0>; # OUTPUT: «False»
To force comparison being done for the L<Stringy> part of the allomorph, use
L«prefix C<~> operator|/routine/~» or the L<Str> method to coerce the allomorph
to L<Str>, or use the L<chars> routine to test whether the allomorph has any length:
say so ~<0>; # OUTPUT: «True»
say so <0>.Str; # OUTPUT: «True»
say so chars <0>; # OUTPUT: «True»
=head2 Case-insensitive comparison of strings
In order to do case-insensitive comparison, you can use C<.fc>
(fold-case). The problem is that people tend to use C<.lc> or C<.uc>,
and it does seem to work within the ASCII range, but fails on other
characters. This is not just a Perl 6 trap, the same applies to other
languages.
=begin code
say ‘groß’.lc eq ‘GROSS’.lc; # ← WRONG; False
say ‘groß’.uc eq ‘GROSS’.uc; # ← WRONG; True, but that's just luck
say ‘groß’.fc eq ‘GROSS’.fc; # ← RIGHT; True
=end code
If you are working with regexes, then there is no need to use C<.fc>
and you can use C<:i> (C<:ignorecase>) adverb instead.
=head1 Pairs
=head2 Constants on the left-hand side of pair notation
Consider this code:
=begin code
enum Animals <Dog Cat>;
my %h := :{ Dog => 42 };
say %h{Dog}; # OUTPUT: «(Any)»
=end code
The C<:{ … }> syntax is used to create
L<object hashes|/type/Hash#Non-string_keys_(object_hash)>. The
intentions of someone who wrote that code were to create a hash with
Enum objects as keys (and C<say %h{Dog}> attempts to get a value using
the Enum object to perform the lookup). However, that's not how pair
notation works.
For example, in C«Dog => 42» the key will be a C<Str>. That is, it
doesn't matter if there is a constant, or an enumeration with the
same name. The pair notation will always use the left-hand side as a
string literal, as long as it looks like an identifier.
To avoid this, use C«(Dog) => 42» or C«::Dog => 42».
=head2 Scalar values within C<Pair>
When dealing with L<Scalar|/type/Scalar> values, the C<Pair> holds
the container to the value. This means that
it is possible to reflect changes to the C<Scalar> value
from outside the C<Pair>:
=begin code
my $v = 'value A';
my $pair = Pair.new( 'a', $v );
$pair.say; # OUTPUT: a => value A
$v = 'value B';
$pair.say; # OUTPUT: a => value B
=end code
Use the method L<freeze|/type/Pair#method_freeze> to force the removal of the
C<Scalar> container from the C<Pair>. For more details see the documentation
about L<Pair|/type/Pair>.
=head1 Sets, bags and mixes
=head2 Sets, bags and mixes do not have a fixed order.
When iterating over this kind of objects, an order is not defined.
=begin code
my $set = <a b c>.Set;
.say for $set.list; # OUTPUT: «a => Truec => Trueb => True»
# OUTPUT: «a => Truec => Trueb => True»
# OUTPUT: «c => Trueb => Truea => True»
=end code
Every iteration might (and will) yield a different order, so you cannot trust on
a particular sequence of the elements of a set. If order does not matter, just
use them that way. If it does, use C<sort>
my $set = <a b c>.Set;
.say for $set.list.sort;# OUTPUT: «a => Trueb => Truec => True»
In general, sets, bags and mixes are unordered, so you should not depend on them
having a particular order.
=head1 Operators
Some operators commonly shared among other languages were repurposed in Perl 6
for other, more common, things:
=head2 Junctions
The C<^>, C<|>, and C<&> are I<not> bitwise operators, they create
L<Junctions|/type/Junction>. The corresponding bitwise operators in Perl 6 are:
C<+^>, C<+|>, C<+&> for integers and C<?^>, C<?|>, C<?&> for booleans.
=head2 Exclusive Sequence Operator
Lavish use of whitespace helps readability, but keep in mind infix operators
cannot have any whitespace in them. One such operator is the sequence operator
that excludes right point: C<...^> (or its L<Unicode
equivalent|/language/unicode_ascii> C<…^>).
say 1... ^5; # OUTPUT: «(1 0 1 2 3 4)»
say 1...^5; # OUTPUT: «(1 2 3 4)»
If you place whitespace between the ellipsis (C<…>) and the caret (C<^>),
it's no longer a single infix operator, but an infix inclusive sequence operator
(C<…>) and a prefix L<Range> operator (C<^>). L«Iterables|/type/Iterable»
are valid endpoints for the sequence operator, so the result you'll get might
not be what you expected.
=head2 String Ranges/Sequences
In some languages, using strings as range end points, considers the entire
string when figuring out what the next string should be; loosely treating the
strings as numbers in a large base. Here's Perl 5 version:
=for code :skip-test
say join ", ", "az".."bc";
# OUTPUT: «az, ba, bb, bc»
Such a range in Perl 6 will produce a different result, where I<each letter>
will be ranged to a corresponding letter in the end point, producing more
complex sequences:
=for code
say join ", ", "az".."bc";
#`{ OUTPUT: «
az, ay, ax, aw, av, au, at, as, ar, aq, ap, ao, an, am, al, ak, aj, ai, ah,
ag, af, ae, ad, ac, bz, by, bx, bw, bv, bu, bt, bs, br, bq, bp, bo, bn, bm,
bl, bk, bj, bi, bh, bg, bf, be, bd, bc
»}
=for code
say join ", ", "r2".."t3";
# OUTPUT: «r2, r3, s2, s3, t2, t3»
To achieve simpler behaviour, similar to the Perl 5 example above, use a
sequence operator that calls C<.succ> method on the starting string:
=for code
say join ", ", ("az", *.succ ... "bc");
# OUTPUT: «az, ba, bb, bc»
=head2 Topicalizing Operators
The smartmatch operator C<~~> and C<andthen> set the topic C<$_> to their
left-hand-side. In conjunction with implicit method calls on the topic this can
lead to surprising results.
=for code
my &method = { note $_; $_ };
$_ = 'object';
say .&method;
# OUTPUT: «objectobject»
say 'topic' ~~ .&method;
# OUTPUT: «topicTrue»
In many cases flipping the method call to the LHS will work.
=for code
my &method = { note $_; $_ };
$_ = 'object';
say .&method;
# OUTPUT: «objectobject»
say .&method ~~ 'topic';
# OUTPUT: «objectFalse»
=head2 Fat Arrow and Constants
The fat arrow operator C«=>» will turn words on its left-hand side to C<Str>
without checking the scope for constants or C<\>-sigiled variables. Use
explicit scoping to get what you mean.
=for code
constant V = 'x';
my %h = V => 'oi‽', ::V => 42;
say %h.perl
# OUTPUT: «{:V("oi‽"), :x(42)}»
=head2 Infix operator assignment
Infix operators, both built in and user defined, can be combined with the
assignment operator as this addition example demonstrates:
my $x = 10;
$x += 20;
say $x; # OUTPUT: «30»
For any given infix operator C<op>, C<L op= R> is equivalent to C<L = L op R>
(where C<L> and C<R> are the left and right arguments, respectively).
This means that the following code may not behave as expected:
my @a = 1, 2, 3;
@a += 10;
say @a; # OUTPUT: «[13]»
Coming from a language like C++, this might seem odd. It is important to bear
in mind that C<+=> isn't defined as method on the left hand argument
(here the C<@a> array) but is simply shorthand for:
my @a = 1, 2, 3;
@a = @a + 10;
say @a; # OUTPUT: «[13]»
Here C<@a> is assigned the result of adding C<@a> (which has three elements)
and C<10>; C<13> is therefore placed in C<@a>.
=head1 Regexes
=head2 C«<{$x}>» vs C«$($x)»: Implicit EVAL
Sometimes you may need to match a generated string in a regex. This can be done
using C<$(…)> or C«<{…}>» syntax:
=for code
my $x = ‘ailemac’;
say ‘I ♥ camelia’ ~~ / $($x.flip) /; # OUTPUT: «「camelia」»
say ‘I ♥ camelia’ ~~ / <{$x.flip}> /; # OUTPUT: «「camelia」»
However, the latter only works I<sometimes>.
Internally C«<{…}>» EVAL-s the given string inside an anonymous regex, while
C<$(…)> lexically interpolates the given string. So C«<{…}>» immediately breaks
with more complicated inputs. For example:
=for code :skip-test
my $x = ‘ailemac#’;
say ‘I ♥ #camelia’ ~~ / $($x.flip) /; # OUTPUT: «「#camelia」»
# ⚠ ↓↓ WRONG ↓↓ ⚠
say ‘I ♥ #camelia’ ~~ / <{$x.flip}> /;
# OUTPUT:
# ===SORRY!===
# Regex not terminated.
# at EVAL_0:1
# ------> anon regex { #camelia}⏏<EOL>
# Malformed regex
# at EVAL_0:1
# ------> anon regex { #camelia}⏏<EOL>
# expecting any of:
# infix stopper
Therefore, try not to use C«<{}>» unless you really need EVAL.
Note that even though EVAL is normally considered unsafe, in this case
it is restricted to a set of safe operations (which is why it works
without L<MONKEY-SEE-NO-EVAL|
/language/pragmas#index-entry-MONKEY-SEE-NO-EVAL-MONKEY-SEE-NO-EVAL> pragma).
In theory, careless use of C«<{}>» will only result in an exception being
thrown, and should not introduce security issues.
=head2 C<|> vs C<||>: which branch will win
To match one of several possible alternatives, C<||> or C<|> will be used. But
they are so different.
When there are multiple matching alternations, for those separated by
C<||>, the first matching alternation wins; for those separated by C<|>,
which to win is decided by LTM strategy. See also:
L<documentation on C<||>|/language/regexes#Alternation:_||> and
L<documentation on C<|>|/language/regexes#Longest_Alternation:_|>.
For simple regexes just using C<||> instead of C<|>
will get you familiar semantics, but if writing grammars then it's useful to
learn about LTM and declarative prefixes and prefer C<|>. And keep yourself
away from using them in one regex. When you have to do that, add parentheses
and ensure that you know how LTM strategy works to make the code
do what you want.
The trap typically arises when you try to mix both C<|> and C<||> in
the same regex:
=for code
say 42 ~~ / [ 0 || 42 ] | 4/; # OUTPUT: «「4」»
say 42 ~~ / [ 42 || 0 ] | 4/; # OUTPUT: «「42」»
The code above may seem like it is producing a wrong result, but the
implementation is actually right.
=head2 C<$/> changes each time a regular expression is matched
Each time a regular expression is matched against something, the special
variable C<$/> holding the result L<Match object|/type/Match>
is changed accordingly to the result of the match (that could also be C<Nil>).
The C<$/> is changed without any regard to the scope the regular expression is matched within.
For further information and examples please see the L<related section in the Regular Expressions documentation|/language/regexes.html#$/_changes_each_time_a_regular_expression_is_matched>.
=head2 C«<foo>» vs. C«< foo>»: named rules vs. quoted lists
Regexes can contain quoted lists; longest token matching is performed on the
list's elements as if a C<|> alternation had been specified (see
L<here|/language/regexes#Quoted_lists_are_LTM_matches> for further information).
Within a regex, the following are lists with a single item, C<'foo'>:
say 'foo' ~~ /< foo >/; # OUTPUT: «「foo」»
say 'foo' ~~ /< foo>/; # OUTPUT: «「foo」»
but this is a call to the named rule C<foo>:
=begin code :skip-test
say 'foo' ~~ /<foo>/;
# OUTPUT: «No such method 'foo' for invocant of type 'Match' in block <unit> at <unknown file> line 1»
=end code
Be wary of the difference; if you intend to use a quoted list, ensure that
whitespace follows the initial C«<».
=head2 Non-capturing, non-global matching in list context
Unlike Perl 5, non-capturing and non-global matching in list context doesn't produce any values:
if 'x' ~~ /./ { say 'yes' } # OUTPUT: «yes»
for 'x' ~~ /./ { say 'yes' } # NO OUTPUT
This is because its 'list' slot (inherited from Capture class) doesn't get populated with the original Match object:
say ('x' ~~ /./).list # OUTPUT: «()»
To achieve the desired result, use global matching, capturing parentheses or a list with a trailing comma:
for 'x' ~~ m:g/./ { say 'yes' } # OUTPUT: «yes»
for 'x' ~~ /(.)/ { say 'yes' } # OUTPUT: «yes»
for ('x' ~~ /./,) { say 'yes' } # OUTPUT: «yes»
=head1 Common Precedence Mistakes
=head2 Adverbs and Precedence