-
Notifications
You must be signed in to change notification settings - Fork 292
/
variables.pod6
1191 lines (891 loc) · 36 KB
/
variables.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
=TITLE Variables
=SUBTITLE Variables in Perl 6
Variable names start with a special character called a I<sigil>, followed
optionally by a second special character named I<twigil> and then an
I<identifier>.
=head1 Sigils
<X|$ (sigil),@ (sigil),% (sigil),& (sigil)>
The sigil serves as a variable indicator and type constraint.
=begin table
Sigil Type constraint Default type Assignment Examples
===== =============== ============ ========== ========
$ Mu (no type constraint) Any item Int, Str, Array, Hash
@ Positional Array list List, Array, Range, Buf
% Associative Hash list Hash, Map, Pair
& Callable Callable item Sub, Method, Block, Routine
=end table
Examples:
my $square = 9 ** 2;
my @array = 1, 2, 3; # Array variable with three elements
my %hash = London => 'UK', Berlin => 'Germany';
X<|is (container type)>
The default type can be set with C<is>.
class FailHash is Hash {
has Bool $!final = False;
multi method AT-KEY ( ::?CLASS:D: Str:D \key ){
fail X::OutOfRange.new(:what("Hash key"), :got(key), :range(self.keys)) if $!final && !self.EXISTS-KEY(key);
callsame
}
method finalize() {
$!final = True
}
}
my %h is FailHash = oranges => "round", bananas => "bendy";
say %h<oranges>;
# OUTPUT «round»
%h.finalize;
say %h<cherry>;
# OUTPUT «Hash key out of range. Is: cherry, should be in (oranges bananas) in method AT-KEY at failhash.p6 line 4 [...]»
Variables without sigils are also possible, see
L<sigilless variables|#Sigilless variables>.
=head2 Item and List Assignment
There are two types of assignment, I<item assignment> and I<list
assignment>. Both use the equal sign C<=> as operator. The distinction
whether an C<=> means item or list assignment is based on the syntax of the
left-hand side.
Item assignment places the value from the right-hand side into the variable
(container) on the left.
List assignment leaves the choice of what to do to the variable on the left.
For example, L<Array> variables (C<@> sigil) empty themselves on list
assignment and then put all the values from the right-hand side into
themselves.
The type of assignment (item or list) is decided by the first context
seen in the current expression or declarator:
my $foo = 5; # item assignment
say $foo.perl; # 5
my @bar = 7, 9; # list assignment
say @bar.WHAT; # Array
say @bar.perl; # [7, 9]<>
(my $baz) = 11, 13; # list assignment
say $baz.WHAT; # (List)
say $baz.perl; # (11, 13)
Thus, the behavior of an assignment contained within a list assignment depends
on the expression or declarator that contains it.
For instance, if the internal assignment is a declarator, item assignment
is used, which has tighter precedence than both the comma and the list
assignment:
my @array;
@array = my $num = 42, "str"; # item assignment: uses declarator
say @array.perl; # [42, "str"]<> (an Array)
say $num.perl; # 42 (a Num)
Similarly, if the internal assignment is an expression that is being
used as an initializer for a declarator, the context of the internal
expression determines the type of assignment:
my $num;
my @array = $num = 42, "str"; # item assignment: uses expression
say @array.perl; # [42, "str"]<> (an Array)
say $num.perl; # 42 (a Num)
my ( @foo, $bar );
@foo = ($bar) = 42, "str"; # list assignment: uses parens
say @foo.perl; # [42, "str"]<> (an Array)
say $bar.perl; # $(42, "str") (a List)
However, if the internal assignment is neither a declarator nor an
expression, but is part of a larger expression, the context of the
larger expression determines the type of assignment:
my ( @array, $num );
@array = $num = 42, "str"; # list assignment
say @array.perl; # [42, "str"]<> (an Array)
say $num.perl; # [42, "str"]<> (an Array)
This is because the whole expression is C<@array = $num = 42, "str">, while
C<$num = 42> is not is own separate expression.
See L<operators|/language/operators> for more details on precedence.
=head2 Sigilless variables
X<|\,sigilless variables>
It is possible to create "variables" in Perl 6 that do not have sigils:
my \degrees = pi / 180;
my \θ = 15 * degrees;
Note, however, that these do not create L<containers|/language/containers>. That means C<degrees>
and C<θ> above actually directly represent C<Num>s. To illustrate, try
assigning to one after you've defined it:
θ = 3; # Dies with the error "Cannot modify an immutable Num"
Sigilless variables do not enforce context, so they can be used to pass
something on as-is:
sub logged(&f, |args) {
say('Calling ' ~ &f.name ~ ' with arguments ' ~ args.perl);
my \result = f(|args);
# ^^^^^^^ not enforcing any context here
say(&f.name ~ ' returned ' ~ result.perl);
return |result;
}
=head1 Twigils
X<|Twigil>
Twigils influence the scoping of a variable. Please be aware that twigils
have no influence over whether the primary sigil interpolates. That is, if
C<$a> interpolates, so do C<$^a>, C<$*a>, C<$=a>, C<$?a>, C<$.a>, etc. It
only depends on the C<$>.
=begin table
Twigil Scope
====== =====
none Based only on declarator
* Dynamic
! Attribute (class member)
? Compile-time variable
. Method (not really a variable)
< Index into match object (not really a variable)
^ Self-declared formal positional parameter
: Self-declared formal named parameter
= Pod variables
~ The sublanguage seen by the parser at this lexical spot
=end table
=head2 The C<*> Twigil
X<|$*>
Dynamic variables are looked up through the caller, not through the outer
scope. For example:
=begin code
my $lexical = 1;
my $*dynamic1 = 10;
my $*dynamic2 = 100;
sub say-all() {
say "$lexical, $*dynamic1, $*dynamic2";
}
# prints 1, 10, 100
say-all();
{
my $lexical = 2;
my $*dynamic1 = 11;
$*dynamic2 = 101;
# prints 1, 11, 101
say-all();
}
# prints 1, 10, 101
say-all();
=end code
The first time C<&say-all> is called, it prints "C<1, 10, 100>" just as one
would expect. The second time though, it prints "C<1, 11, 101>". This is
because C<$lexical> isn't looked up in the caller's scope but in the scope
C<&say-all> was defined in. The two dynamic variables are looked up in the
caller's scope and therefore have the values C<11> and C<101>. The third
time C<&say-all> is called C<$*dynamic1> isn't C<11> anymore, but
C<$*dynamic2> is still C<101>. This stems from the fact that we declared a
new dynamic variable C<$*dynamic1> in the block and did not assign to the
old variable as we did with C<$*dynamic2>.
The dynamic variables differ from other variable types in that referring
to an undeclared dynamic variable is not a compile time error but a
runtime L<failure|/type/Failure>, so a dynamic variable can be used
undeclared as long as it is checked for definedness or used in a
boolean context before using it for anything else:
=begin code
sub foo() {
$*FOO // 'foo';
}
say foo; # -> 'foo'
my $*FOO = 'bar';
say foo; # -> 'bar'
=end code
=head2 The C<!> Twigil
X<|$!>
Attributes are variables that exist per instance of a class. They may be
directly accessed from within the class via C<!>:
=begin code
class Point {
has $.x;
has $.y;
method Str() {
"($!x, $!y)"
}
}
=end code
Note how the attributes are declared as C<$.x> and C<$.y> but are still
accessed via C<$!x> and C<$!y>. This is because in Perl 6 all attributes are
private and can be directly accessed within the class by using
C<$!attribute-name>. Perl 6 may automatically generate accessor methods for
you though. For more details on objects, classes and their attributes see
L<object orientation|/language/objects>.
=head2 The C<?> Twigil
X<|$?>
Compile-time variables may be addressed via the C<?> twigil. They are known
to the compiler and may not be modified after being compiled in. A popular
example for this is:
say "$?FILE: $?LINE"; # prints "hello.pl: 23" if this is the 23 line of a
# file named "hello.pl".
Although they may not be changed at runtime, the user is allowed to
(re)define such variables.
constant $?TABSTOP = 4; # this causes leading tabs in a heredoc or in a POD
# block's virtual margin to be counted as 4 spaces.
For a list of these special variables see
L<compile-time variables|/language/variables#Compile-time_variables>.
=head2 The C<.> Twigil
X<|$.>
The C<.> twigil isn't really for variables at all. In fact, something along
the lines of
=begin code
class Point {
has $.x;
has $.y;
method Str() {
"($.x, $.y)" # note that we use the . instead of ! this time
}
}
=end code
just calls the methods C<x> and C<y> on C<self>, which are automatically
generated for you because you used the C<.> twigil when the attributes were
declared. Note, however, that subclasses may override those methods. If you
don't want this to happen, use C<$!x> and C<$!y> instead.
The fact that the C<.> twigil just does a method call also implies that the
following is possible too:
=begin code
class SaySomething {
method a() { say "a"; }
method b() { $.a; }
}
SaySomething.b; # prints "a"
=end code
For more details on objects, classes and their attributes and methods see
L<object orientation|/language/objects>.
=head2 The C«<» Twigil
The C<< < >> twigil is just an alias for C<< $/<...> >> where C<$/> is the
match variable. For more information about the match variable see L<$/> and
L<type Match|/type/Match>.
=head2 The C<^> Twigil
X<|$^>
The C<^> twigil declares a formal positional parameter to blocks or
subroutines. Variables of the form C<$^variable> are a type of placeholder
variable. They may be used in bare blocks to declare formal parameters to
that block. So the block in the code
=for code :allow<B>
for ^4 {
say "B<$^b> follows B<$^a>";
}
which prints
1 follows 0
3 follows 2
has two formal parameters, namely C<$a> and C<$b>. Note that even though C<$^b>
appears before C<$^a> in the code, C<$^a> is still the first formal parameter
to that block. This is because the placeholder variables are sorted in Unicode
order. If you have self-declared a parameter using C<$^a> once, you may refer
to it using only C<$a> thereafter.
Although it is possible to use nearly any valid identifier as a placeholder
variable, it's recommended to use short names or ones that can be trivially
understood in the correct order, to avoid surprise on behalf of the reader.
Subroutines may also make use of placeholder variables but only if they do
not have an explicit parameter list. This is true for normal blocks too.
sub say-it { say $^a; } # valid
sub say-it() { say $^a; } # invalid
{ say $^a; } # valid
-> $x, $y, $x { say $^a; } # invalid
Placeholder variables syntactically cannot have any type constraints. Be
also aware that one cannot have placeholder variables with a single
upper-case letter. This is disallowed in favor of being to able to catch
some Perl 5-isms.
=head2 The C<:> Twigil
X<|$:>
The C<:> twigil declares a formal named parameter to a block or subroutine.
Variables declared using this form are a type of placeholder variable too.
Therefore the same things that apply to variables declared using the C<^>
twigil also apply here (with the exception that they are not positional and
therefore not ordered using Unicode order, of course). So this:
=for code :allow<B>
say { B<$:add> ?? $^a + $^b !! $^a - $^b }( 4, 5 ) :!add
Will print "C<-1>".
See L<^> for more details about placeholder variables.
=head2 The C<=> Twigil
X<|$=>
The C<=> twigil is used to access Pod variables. Every Pod block in the
current file can be accessed via a Pod object, such as C<$=data>,
C<$=SYNOPSIS> or C<=UserBlock>. That is: a variable with the same name of
the desired block and a C<=> twigil.
=begin code
=begin Foo
...
=end Foo
#after that, $=Foo gives you all Foo-Pod-blocks
=end code
You may access the Pod tree which contains all Pod structures as a
hierarchical data structure through C<$=pod>.
Note that all those C<$=someBlockName> support the C<Positional> and the
C<Associative> roles.
=head2 The C<~> Twigil
X<|$~>
Note: Slangs are L<NYI|/language/glossary#NYI> in Rakudo.
The C<~> twigil is for referring to sublanguages (called slangs). The
following are useful:
X<|$~MAIN>X<|$~Quote>X<|$~Quasi>X<|$~Regex>X<|$~Trans>X<|$~P5Regex>
$~MAIN the current main language (e.g. Perl statements)
$~Quote the current root of quoting language
$~Quasi the current root of quasiquoting language
$~Regex the current root of regex language
$~Trans the current root of transliteration language
$~P5Regex the current root of the Perl 5 regex language
You may C<supersede> or C<augment> these languages in your current lexical
scope by using
augment slang Regex { # derive from $~Regex and then modify $~Regex
token backslash:std<\Y> { YY };
}
or
supersede slang Regex { # completely substitute $~Regex
...
}
=head1 Variable Declarators and Scope
Most of the time it's enough to create a new variable using the C<my>
keyword:
=for code :allow<B>
B<my> $amazing-variable = "World";
say "Hello $amazing-variable!"; # Hello World!
However, there are many declarators that change the details of scoping
beyond what L<#Twigils> can do.
=for table
Declarator Effect
========== ======
my Introduces lexically scoped names
our Introduces package-scoped names
has Introduces attribute names
anon Introduces names that are private to the construct
state Introduces lexically scoped but persistent names
augment Adds definitions to an existing name
supersede Replaces definitions of an existing name
There are also two prefixes that resemble declarators but act on
predefined variables:
=for table
Prefix Effect
====== ======
temp Restores a variable's value at the end of scope
let Restores a variable's value at the end of scope if the block exits unsuccessfully
=head2 The C<my> Declarator
Declaring a variable with C<my> gives it lexical scope. This means it only
exists within the current block. For example:
{
my $foo = "bar";
say $foo; # -> "bar"
}
say $foo; # !!! "Variable '$foo' is not declared"
This dies because C<$foo> is only defined as long as we are in the same
scope.
Additionally, lexical scoping means that variables can be temporarily
redefined in a new scope:
=begin code
my $location = "outside";
sub outer-location {
# Not redefined:
say $location;
}
outer-location; # -> "outside"
sub in-building {
my $location = "inside";
say $location;
}
in-building; # -> "inside"
outer-location; # -> "outside"
=end code
If a variable has been redefined, any code that referenced the outer
variable will continue to reference the outer variable. So here,
C<&outer-location> still prints the outer C<$location>:
=begin code
sub new-location {
my $location = "nowhere"
outer-location;
}
new-location; # -> "outside"
=end code
To make C<new-location()> print C<nowhere>, make C<$location> a dynamic
variable using L<the * twigil|#The_*_Twigil>.
C<my> is the default scope for subroutines, so C<my sub x() {}> and
C<sub x() {}> do exactly the same thing.
=head2 The C<our> Declarator
C<our> variables work just like C<my> variables, except that they also
introduce an alias into the symbol table.
module M {
our $Var;
# $Var available here
}
# Available as $M::Var here.
=head2 The C<has> Declarator
C<has> scopes attributes to instances of a class or role, and methods to
classes or roles. C<has> is implied for methods, so C<has method x() {}>
and C<method x() {}> do the same thing.
See L<object orientation|/language/objects> for more documentation and some
examples.
=head2 The C<anon> Declarator
The C<anon> declarator prevents a symbol from getting installed in the lexical
scope, the method table and everywhere else.
For example you can use it to declare subroutines which know their own name,
but still aren't installed in a scope:
my %operations =
half => anon sub half($x) { $x / 2 },
square => anon sub square($x) { $x * $x },
;
say %operations<square>.name; # square
say %operations<square>(8); # 64
=head2 The C<state> Declarator
C<state> declares lexically scoped variables, just like C<my>. However,
initialization happens exactly once the first time the initialization
is encountered in the normal flow of execution. Thus, state variables
will retain their value across multiple executions of the enclosing
block or routine.
Therefore, the subroutine
=begin code
sub a {
state @x;
state $l = 'A';
@x.push($l++);
};
say a for 1..6;
This works per "clone" of the containing code object, so:
({ state $i = 1; $i++.say; } xx 3).map: {$_(), $_()}; # says 1 then 2 thrice
Note that this is B<not> a thread-safe construct when the same clone of the same
block is run by multiple threads. Also remember that methods only have one
clone per class, not per object.
=end code
will continue to increment C<$l> and append it to C<@x> each time it is
called. So it will output
=begin code
[A]
[A B]
[A B C]
[A B C D]
[A B C D E]
[A B C D E F]
=end code
As with C<my>, declaring multiple C<state> variables must be placed
in parentheses and for declaring a single variable, parentheses may
be omitted.
Please note that many operators come with implicit binding, what will lead to actions at a distance. Use C<.clone> or coercion to create a new container that can be bound to.
my @a;
sub f() {
state $i;
$i++;
@a.push: "k$i" => $i # <-- .clone goes here
};
f for 1..3;
dd @a; # «Array $var = $[:k1(3), :k2(3), :k3(3)]»
All state variables are shared between threads. The result can be undesired or
dangerous.
sub code(){ state $i = 0; say ++$i; $i };
await
start { loop { last if code() >= 5 } },
start { loop { last if code() >= 5 } };
# OUTPUT«1234435»
# OUTPUT«21345»
# many other more or less odd variations can be produced
=head3 The C<$> Variable
As well as explicitly declared named state variables C<$> can be used
as an anonymous state variable without an explicit C<state> declaration:
=begin code
perl6 -e 'sub foo() { say ++$ }; foo() for ^3'
=end code
produces:
=begin code
1
2
3
=end code
Furthermore, state variables are not required to exist in subroutines. You
could, for example, use C<$> in a one-liner to number the lines in a file:
=begin code
perl6 -ne 'say ++$ ~ " $_"' example.txt
=end code
Each reference to C<$> within a lexical scope in effect is a separate
variable, as illustrated by:
=begin code
perl6 -e '{ say ++$; say $++ } for ^5'
=end code
which produces:
=begin code
1
0
2
1
3
2
4
3
5
4
=end code
If you need to refer to the value of C<$> more than once within the
scope it should be copied to a new variable, for example:
=begin code
sub foo() {
given ++$ {
when 1 {
say "one";
}
when 2 {
say "two";
}
when 3 {
say "three";
}
default {
say "many";
}
}
}
foo() for ^3;
=end code
produces:
=begin code
one
two
three
=end code
=head3 The C<@> Variable
In a similar manner to the C<$> variable there is also a L<Positional>
anonymous state variable C<@> :
=begin code
sub foo($x) {
say (@).push($x);
}
foo($_) for ^3;
=end code
Produces:
=begin code
[0]
[0 1]
[0 1 2]
=end code
The C<@> here is parenthesized in order to disambiguate the expression
from a class member variable named C<@.push>. Indexed access doesn't
require this disambiguation but you will need to copy the value in order
to do anything useful with it:
=begin code
sub foo($x) {
my $v = @;
$v[$x] = $x;
say $v;
}
foo($_) for ^3;
=end code
Produces:
=begin code
[0]
[0 1]
[0 1 2]
=end code
As with C<$> each mention of C<@> in a scope introduces a new anonymous
array.
=head3 The C<%> Variable
Finally there is also an L<Associative> anonymous state variable C<%>:
=begin code
sub foo($x) {
say (%).push($x => $x);
}
foo($_) for ^3;
=end code
Which produces:
=begin code
0 => 0
0 => 0, 1 => 1
0 => 0, 1 => 1, 2 => 2
=end code
The same caveat about disambiguation applies. As you may expect, indexed
access is also possible (with copying to make it useful):
=begin code
sub foo($x) {
my $v = %;
$v{$x} = $x;
say $v;
}
foo($_) for ^3;
=end code
Which produces:
=begin code
0 => 0
0 => 0, 1 => 1
0 => 0, 1 => 1, 2 => 2
=end code
As with the other anonymous state variables each mention of C<%> within a
given scope will effectively introduce a separate variable.
=head2 The C<augment> Declarator
With C<augment>, you can add attributes and methods to existing classes and
grammars, provided you activated the C<MONKEY-TYPING> pragma first.
Since classes are usually C<our> scoped, and thus global, this means modifying
global state, which is strongly discouraged. For almost all situations, there
are better solutions.
# don't do this
use MONKEY-TYPING;
augment class Int {
method is-answer { self == 42 }
}
say 42.is-answer; # True
(In this case, the better solution would be to use a
L<function|/language/functions>).
=head2 The C<temp> Prefix
Like C<my>, C<temp> restores the old value of a variable at the end of its
scope. However, C<temp> does not create a new variable.
my $in = 0; # temp will "entangle" the global variable with the call stack
# that keeps the calls at the bottom in order.
sub f(*@c) {
(temp $in)++;
"<f>\n"
~ @c>>.indent($in).join("\n")
~ (+@c ?? "\n" !! "")
~ '</f>'
};
sub g(*@c) {
(temp $in)++;
"<g>\n"
~ @c>>.indent($in).join("\n")
~ (+@c ?? "\n" !! "")
~ "</g>"
};
print g(g(f(g()), g(), f()));
output:
<g>
<g>
<f>
<g>
</g>
</f>
<g>
</g>
<f>
</f>
</g>
</g>
=head2 The C<let> Prefix
Restores the previous value if the block exits unsuccessfully. A
successful exit means the block returned a defined value or a list.
my $answer = 42;
{
let $answer = 84;
die if not Bool.pick;
CATCH {
default { say "it's been reset :(" }
}
say "we made it 84 sticks!";
}
say $answer;
In the above case, if the C<Bool.pick> returns true, the answer will
stay as 84 because the block returns a defined value (C<say> returns
true). Otherwise the C<die> statement will cause the block to exit
unsuccessfully, resetting the answer to 42.
=comment this is duplicated in operators.pod
=head1 Type Constraints and Initialization
Variables can have a type constraint, which goes between the declarator and
the variable name:
=begin code :allow<L>
my Int $x = 42;
$x = 'a string'; # throws an L<X::TypeCheck::Assignment|/type/X::TypeCheck::Assignment> error
=end code
If a scalar variable has a type constraint but no initial value, it is
initialized with the type object of the constraint type.
my Int $x;
say $x.^name; # Int
say $x.defined; # False
Scalar variables without an explicit type constraint are typed as
L<Mu|/type/Mu> but default to the L<Any|/type/Any> type object.
Variables with the C<@> sigil are initialized with an empty
L<Array|/type/Array>; variables with the C<%> sigil are initialized with an
empty L<Hash|/type/Hash>.
The default value of a variable can be set with the C<is default> trait, and
re-applied by assigning C<Nil> to it:
my Real $product is default(1);
say $product; # 1
$produce *= 5;
say $product; # 5
$product = Nil;
say $product; # 1
=head2 Default Defined Variables Pragma
To force all variables to have a definedness contraint use the prama C<use
variables :D>. The pragma is lexically scoped and can be switched of with C<use
variables :_>.
use variables :D;
my Int $i;
# OUTPUT«===SORRY!=== Error while compiling <tmp>Variable definition of type Int:D (implicit :D by pragma) requires an initializer ...
my Int $i = 1; # that works
{ use variables :_; my Int $i; } # switch it off in this block
Please note that assigning L<Nil|/type/Nil> will revert the variable to it's
default value. The default value of a defined constraint type is the type
appended with C<:D> (e.g. C<Int:D>). That means a definedness contraint is no
guarantee of definedness. This only applies to variable initializers, not to
L<Signature|/type/Signature>s. or subsequent assignments to a variable.
=head1 Special Variables
Perl 5 is infamous for its many obscure special variables. Perl 6 also has
special variables but only has three that are extra short due to how often
they're used. Other special variables have longer, more descriptive names.
=head2 Pre-defined lexical variables
There are three special variables that are available in every block:
=begin table
Variable Meaning
$_ topic variable
$/ regex match
$! exceptions
=end table
=head3 The C<$_> Variable
C<$_> is the topic variable. It is the default parameter for blocks that do
not have an explicit signature, so constructs like C<for @array { ... }> and
C<given $var { ... }> bind to C<$_> simply by invoking the block.
for <a b c> { say $_ } # sets $_ to 'a', 'b' and 'c' in turn
say $_ for <a b c>; # same, even though it's not a block
given 'a' { say $_ } # sets $_ to 'a'
say $_ given 'a'; # same, even though it's not a block
C<CATCH> blocks set C<$_> to the exception that was caught. The C<~~>
smart-match operator sets C<$_> on the right-hand side expression to the
value of the left-hand side.
Calling a method on C<$_> can be shortened by leaving off the variable name:
.say; # same as $_.say
C<m/regex/> and C</regex/> regex matches and C<s/regex/subst/> substitutions
work on C<$_>:
say "Looking for strings with non-alphabetic characters...";
for <ab:c d$e fgh ij*> {
.say if m/<!alpha>/;
}
This outputs:
Looking for strings with non-alphabetic characters...
ab:c
d$e
ij*
=head3 The C<$/> Variable
C<$/> is the match variable. It stores the result of the last L<Regex|/language/regexes>
match and so usually contains objects of type L<Match>.
'abc 12' ~~ /\w+/; # sets $/ to a Match object