/
S04-control.pod
1828 lines (1420 loc) · 77.9 KB
/
S04-control.pod
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
=encoding utf8
=head1 TITLE
Synopsis 4: Blocks and Statements
=head1 AUTHORS
Larry Wall <larry@wall.org>
=head1 VERSION
Created: 19 Aug 2004
Last Modified: 28 Jul 2012
Version: 118
This document summarizes Apocalypse 4, which covers the block and
statement syntax of Perl.
=head1 The Relationship of Lexical and Dynamic Scopes
Control flow is a dynamic feature of all computer programming
languages, but languages differ in the extent to which control flow is
attached to declarative features of the language, which are often known
as "static" or "lexical". We use the phrase "lexical scoping" in its
industry-standard meaning to indicate those blocks that surround the
current textual location. More abstractly, any declarations associated
with those textual blocks are also considered to be part of the lexical
scope, and this is where the term earns the "lexical" part of its name,
in the sense that lexical scoping actually does define the "lexicon"
for the current chunk of code, insofar as the definitions of variables
and routines create a local domain-specific language.
We also use the term "dynamic scoping" in the standard fashion to
indicate the nested call frames that are created and destroyed every
time a function or method is called. In most interesting programs the
dynamic scopes are nested quite differently from the lexical scopes,
so it's important to distinguish carefully which kind of scoping
we're talking about.
Further compounding the difficulty is that every dynamic scope's outer call frame is
associated with a lexical scope somewhere, so you can't just consider
one kind of scoping or the other in isolation. Many constructs define
a particular interplay of lexical and dynamic features. For instance,
unlike normal lexically scope variables, dynamic variables search
up the dynamic call stack for a variable of a particular name, but at
each "stop" along the way, they are actually looking in the lexical
"pad" associated with that particular dynamic scope's call frame.
In Perl 6, control flow is designed to do what the user expects most of
the time, but this implies that we must consider the declarative nature
of labels and blocks and combine those with the dynamic nature of the
call stack. For instance, a C<return> statement always returns from
the lexically scoped subroutine that surrounds it. But to do that,
it may eventually have to peel back any number of layers of dynamic
call frames internal to the subroutine's current call frame. The lexical scope supplies the
declared target for the dynamic operation. There does not seem to
be a prevailing term in the industry for this, so we've coined the
term I<lexotic> to refer to these strange operations that perform a
dynamic operation with a lexical target in mind. Lexotic operators
in Perl 6 include:
return
next
last
redo
goto
Some of these operators also fall back to a purely dynamic interpretation
if the lexotic interpretation doesn't work. For instance, C<next> with a label
will prefer to exit a loop lexotically, but if there is no loop with
an appropriate label in the lexical context, it will then scan upward
dynamically through the call frames for any loop with the appropriate label, even though that
loop will not be lexically visible. (C<next> without a label is purely dynamic.) Lexotic and dynamic control flow
is implemented by a system of control exceptions. For the lexotic
return of C<next>, the control exception will contain the identity of
the loop scope to be exited (since the label was already "used up" to
discover that identity), but for the dynamic fallback, the exception
will contain only the loop label to be matched dynamically. See
L</Control Exceptions> below.
=head1 The Relationship of Blocks and Declarations
Every block is a closure. (That is, in the abstract, they're all
anonymous subroutines that take a snapshot of their lexical environment.)
How a block is invoked and how its results are used are matters of
context, but closures all work the same on the inside.
Blocks are delimited by curlies, or by the beginning and end of the
current compilation unit (either the current file or the current
C<eval> string). Unlike in Perl 5, there are (by policy) no implicit
blocks around standard control structures. (You could write a macro
that violates this, but resist the urge.) Variables that mediate
between an outer statement and an inner block (such as loop variables)
should generally be declared as formal parameters to that block. There
are three ways to declare formal parameters to a closure.
$func = sub ($a, $b) { .print if $a eq $b }; # standard sub declaration
$func = -> $a, $b { .print if $a eq $b }; # a "pointy" block
$func = { .print if $^a eq $^b } # placeholder arguments
A bare closure (except the block associated with a conditional statement)
without placeholder arguments that uses C<$_>
(either explicitly or implicitly) is treated as though C<$_> were a
formal parameter:
$func = { .print if $_ }; # Same as: $func = <-> $_ { .print if $_ };
$func("printme");
In any case, all formal parameters are the equivalent of C<my> variables
within the block. See S06 for more on function parameters.
Except for such formal parameter declarations, all lexically scoped
declarations are visible from the point of declaration to the end of
the enclosing block. Period. Lexicals may not "leak" from a block to any
other external scope (at least, not without some explicit aliasing
action on the part of the block, such as exportation of a symbol
from a module). The "point of declaration" is the moment the compiler
sees "C<my $foo>", not the end of the statement as in Perl 5, so
my $x = $x;
will no longer see the value of the outer C<$x>; you'll need to say
either
my $x = $OUTER::x;
or
my $x = OUTER::<$x>;
instead.
If you declare a lexical twice in the same scope, it is the same lexical:
my $x;
my $x;
By default the second declaration will get a compiler warning.
You may suppress this by modifying the first declaration
with C<proto>:
my proto $x;
...
while my $x = @x.shift {...} # no warning
while my $x = @x.shift {...} # no warning
If you've referred to C<$x> prior to the first declaration, and the compiler
tentatively bound it to C<$OUTER::x>, then it's an error to declare it, and
the compiler is required to complain at that point. If such use can't
be detected because it is hidden in an eval, then it is erroneous, since
the C<eval()> compiler might bind to either C<$OUTER::x> or the subsequently
declared "C<my $x>".
As in Perl 5, "C<our $foo>" introduces a lexically scoped alias for
a variable in the current package.
The new C<constant> declarator introduces a
compile-time constant, either a variable or named value, which
may be initialized with a pseudo-assignment:
constant $pi of Int = 3;
my Num constant π = atan2(2,2) * 4;
The initializing expression is evaluated at C<BEGIN> time. Constants
(and enums) default to C<our> scoping so they can be accessed from
outside the package.
There is a new C<state> declarator that introduces a lexically scoped
variable like C<my> does, but with a lifetime that persists for the
life of the closure, so that it keeps its value from the end of one
call to the beginning of the next. Separate clones of the closure
get separate state variables. However, recursive calls to the same
clone use the same state variable.
Perl 5's "C<local>" function has been renamed to C<temp> to better
reflect what it does. There is also a C<let> prefix operator that sets a
hypothetical value. It works exactly like C<temp>, except that the
value will be restored only if the current block exits unsuccessfully.
(See Definition of Success below for more.) C<temp> and C<let> temporize
or hypotheticalize the value or the variable depending on whether you
do assignment or binding. One other difference from Perl 5 is that
the default is not to undefine a variable. So
temp $x;
causes C<$x> to start with its current value. Use
temp undefine $x;
to get the Perl 5 behavior.
Note that temporizations that are undone upon scope exit must be
prepared to be redone if a continuation within that scope is taken.
=head1 The Relationship of Blocks and Statements
In the absence of explicit control flow terminating the block early,
the return value of a block is the value of its final statement.
This is defined as the textually last statement of its top-level
list of statements; any statements embedded within those top-level
statements are in their own lower-level list of statements and,
while they may be a final statement in their subscope, they're not
considered the final statement of the outer block in question.
This is subtly different from Perl 5's behavior, which was to return
the value of the last expression evaluated, even if that expression
was just a conditional. Unlike in Perl 5, if a final statement in
Perl 6 is a conditional that does not execute any of its branches, it
doesn't matter what the value of the conditional is, the value of that
conditional statement is always C<Nil>. If there are no statements
in the block at all, the result is also C<Nil>.
=head1 Statement-ending blocks
A line ending with a closing brace "C<}>", followed by nothing but
whitespace or comments, will terminate a statement if an end of statement
can occur there. That is, these two statements are equivalent:
my $x = sub { 3 }
my $x = sub { 3 };
Since bracketed expressions consider their insides to be statements,
this works out consistently even where you might expect problems:
my $x = [
sub { 3 }, # this comma is not optional
sub { 3 } # the statement inside [] terminates here
];
my $hash = {
1 => { 2 => 3, 4 => 5 }, # OK
2 => { 6 => 7, 8 => 9 } # OK, terminates inner statement
};
Because subroutine declarations are expressions, not statements,
this is now invalid:
sub f { 3 } sub g { 3 } # two terms occur in a row
But these two are valid:
sub f { 3 }; sub g { 3 };
sub f { 3 }; sub g { 3 } # the trailing semicolon is optional
Though certain control statements could conceivably be parsed in a
self-contained way, for visual consistency all statement-terminating
blocks that end in the middle of a line I<must> be terminated by
semicolon unless they are naturally terminated by some other statement
terminator:
while yin() { yang() } say "done"; # ILLEGAL
while yin() { yang() }; say "done"; # okay, explicit semicolon
@yy := [ while yin() { yang() } ]; # okay within outer [...]
while yin() { yang() } ==> sort # okay, ==> separates statements
=head1 Conditional statements
X<if>X<unless>
The C<if> and C<unless> statements work much as they do in
Perl 5. However, you may omit the parentheses on the conditional:
if $foo == 123 {
...
}
elsif $foo == 321 {
...
}
else {
...
}
The result of a conditional statement is the result of the block
chosen to execute. If the conditional does not execute any
branch, the return value is C<Nil>.
The C<unless> statement does not allow an C<elsif> or C<else> in Perl 6.
The value of the conditional expression may be optionally bound to
a closure parameter:
if testa() -> $a { say $a }
elsif testb() -> $b { say $b }
else -> $b { say $b }
Note that the value being evaluated for truth and subsequently bound is
not necessarily a value of type C<Bool>. (All normal types in Perl may
be evaluated for truth. In fact, this construct would be relatively
useless if you could bind only boolean values as parameters, since
within the closure you already know whether it evaluated to true
or false.) Binding within an C<else> automatically binds the value
tested by the previous C<if> or C<elsif>, which, while known to be
false, might nevertheless be an I<interesting> value of false. (By similar
reasoning, an C<unless> allows binding of a false parameter.)
An explicit placeholder may also be used:
if blahblah() { return $^it }
However, use of C<$_> with a conditional or conditionally repeating
statement's block is I<not> considered sufficiently explicit to turn
a 0-ary block into a 1-ary function, so all these methods use the
same invocant:
if .haste { .waste }
while .haste { .waste }
(Contrast with a non-conditional statement such as:
for .haste { .waste }
where each call to the block would bind a new invocant for the
C<.waste> method, each of which is likely different from the original
invocant to the C<.haste> method.)
Conditional statement modifiers work as in Perl 5. So do the
implicit conditionals implied by short-circuit operators. Note though that
the contents of parens or brackets is parsed as a semicolon-separated list of
I<statements>,
so you can say:
@x = 41, (42 if $answer), 43;
and that is equivalent to:
@x = 41, ($answer ?? 42 !! Nil), 43
=head1 Loop statements
Looping statement modifiers are the same as in Perl 5 except that,
for ease of writing list comprehensions, a looping statement modifier
is allowed to contain a single conditional statement modifier:
@evens = ($_ * 2 if .odd for 0..100);
Loop modifiers C<next>, C<last>, and C<redo> also work much as in
Perl 5. However, the labeled forms can use method call syntax:
C<LABEL.next>, etc. The C<.next> and C<.last> methods take an
optional argument giving the final value of that loop iteration.
So the old C<next LINE> syntax is still allowed but really does
something like C<LINE.next(Nil)> underneath. Any block object can
be used, not just labels, so to return a value from this iteration
of the current block you can say:
&?BLOCK.next($retval);
[Conjecture: a bare C<next($retval)> function could be taught to do
the same, as long as C<$retval> isn't a loop label. Presumably multiple
dispatch could sort this out.]
With a target object or label, loop modifiers search lexotically
for the scope to modify. Without a target, however, they are purely
dynamic, and choose the innermost dynamic loop, which may well be a
C<map> or other implicitly looping function, including user-defined
functions.
There is no longer a C<continue> block. Instead, use a C<NEXT> block
within the body of the loop. See below.
The value of a loop statement is the list of values from each
iteration. Each iteration's value is returned as a single "argument"
object. See L<S02> for a long definition of argument, but in short,
it's either an ordinary object or a parcel containing multiple values.
Normal flat list context ignores parcel boundaries and flattens the list.
Slice context turns any parcel objects into C<Seq> objects.
Iterations that return C<Nil> (such as by calling C<next> with no extra return
arguments) return that C<Nil> as the next value, which will therefore disappear
when interpolated in flat context, but will interpolate an empty C<Seq> into slice
context.
For finer-grained control of which iterations return values, use
C<gather> and C<take>.
Since the final expression in a subroutine returns its value, it's
possible to accidentally return a loop's return value when you were
only evaluating the loop for its side effects. If you do not wish
to accidentally return a list from the final loop statement in a
subroutine, place an explicit return statement after it, or use a C<sink>
statement prefix on the loop itself.
=head2 The C<while> and C<until> statements
X<while>X<until>
The C<while> and C<until> statements work as in Perl 5, except that you
may leave out the parentheses around the conditional:
while $bar < 100 {
...
}
As with conditionals, you may optionally bind the result of the
conditional expression to a parameter of the block:
while something() -> $thing {
...
}
while something() { ... $^thing ... }
Nothing is ever bound implicitly, however, and many conditionals would
simply bind C<True> or C<False> in an uninteresting fashion. This mechanism
is really only good for objects that know how to return a boolean
value and still remain themselves. In general, for most iterated
solutions you should consider using a C<for> loop instead (see below).
In particular, we now generally use C<for> to iterate filehandles.
=head2 The C<repeat> statement
X<repeat>X<while>X<next>X<last>X<redo>
Unlike in Perl 5, applying a statement modifier to a C<do> block is
specifically disallowed:
do {
...
} while $x < 10; # ILLEGAL
Instead, you should write the more Pascal-like C<repeat> loop:
repeat {
...
} while $x < 10;
or equivalently:
repeat {
...
} until $x >= 10;
Unlike Perl 5's C<do-while> loop, this is a real loop block now, so
C<next>, C<last>, and C<redo> work as expected. The loop conditional
on a C<repeat> block is required, so it will be recognized even if you
put it on a line by its own:
repeat
{
...
}
while $x < 10;
However, that's likely to be visually confused with a following
C<while> loop at the best of times, so it's also allowed to put the
loop conditional at the front, with the same meaning. (The C<repeat>
keyword forces the conditional to be evaluated at the end of the loop,
so it's still C's C<do-while> semantics.) Therefore, even under GNU style
rules, the previous example may be rewritten into a very clear:
repeat while $x < 10
{
...
}
or equivalently:
repeat until $x >= 10
{
...
}
As with an ordinary C<while>, you may optionally bind the result of
the conditional expression to a parameter of the block:
repeat -> $thing {
...
} while something();
or
repeat while something() -> $thing {
...
}
Since the loop executes once before evaluating the condition, the
bound parameter will be undefined that first time through the loop.
=head2 The general loop statement
X<loop>
The C<loop> statement is the C-style C<for> loop in disguise:
loop ($i = 0; $i < 10; $i++) {
...
}
As in C, the parentheses are required if you supply the 3-part spec; however,
the 3-part loop spec may be entirely omitted to write an infinite loop.
That is,
loop {...}
is equivalent to the Cish idiom:
loop (;;) {...}
=head2 The C<for> statement
X<for>X<zip>X<Z>X<STDIN>X<$*IN>X<lines>
There is no C<foreach> statement any more. It's always spelled C<for>
in Perl 6, so it always takes a list as an argument:
for @foo { .print }
As mentioned earlier, the loop variable is named by passing a parameter
to the closure:
for @foo -> $item { print $item }
Multiple parameters may be passed, in which case the list is traversed
more than one element at a time:
for %hash.kv -> $key, $value { print "$key => $value\n" }
To process two arrays in parallel use the C<zip> function to generate a
list that can be bound to the corresponding number of parameters:
for zip(@a;@b) -> $a, $b { print "[$a, $b]\n" }
for @a Z @b -> $a, $b { print "[$a, $b]\n" } # same thing
The list is evaluated lazily by default, so instead of using a C<while>
to read a file a line at a time as you would in Perl 5:
while (my $line = <STDIN>) {...}
in Perl 6 you should use a C<for> instead:
for $*IN.lines -> $line {...}
This has the added benefit of limiting the scope of the C<$line>
parameter to the block it's bound to. (The C<while>'s declaration of
C<$line> continues to be visible past the end of the block. Remember,
no implicit block scopes.) It is also possible to write
while $*IN.get -> $line {...}
However, this is likely to fail on autochomped filehandles, so use
the C<for> loop instead.
Note also that Perl 5's special rule causing
while (<>) {...}
to automatically assign to C<$_> is not carried over to Perl 6. That
should now be written:
for lines() {...}
which is short for
for lines($*ARGFILES) {...}
Arguments bound to the formal parameters of a pointy block are by
default readonly within the block. You can declare a parameter
read/write by including the "C<is rw>" trait. The following treats
every other value in C<@values> as modifiable:
for @values -> $even is rw, $odd { ... }
In the case where you want all your parameters to default to C<rw>,
you may use the visually suggestive double-ended arrow to indicate that
values flow both ways:
for @values <-> $even, $odd { ... }
This is equivalent to
for @values -> $even is rw, $odd is rw { ... }
If you rely on C<$_> as the implicit parameter to a block,
then C<$_> is considered read/write by default. That is,
the construct:
for @foo {...}
is actually short for:
for @foo <-> $_ {...}
so you can modify the current list element in that case.
When used as statement modifiers on implicit blocks (thunks), C<for>
and C<given> privately temporize the current value of C<$_> for the
left side of the statement and restore the original value at loop exit:
$_ = 42;
.say # 42
.say for 1,2,3; # 1,2,3
.say; # 42
The previous value of C<$_> is not available within the loop. If you
want it to be available, you must rewrite it as an explicit block
using curlies:
{ say OUTER::<$_>, $_ } for 1,2,3; # 421,422,423
No temporization is necessary with the explicit form since C<$_> is a
formal parameter to the block. Likewise, temporization is never needed
for C<< statement_control:<for> >> because it always calls a closure.
=head2 The do-once loop
In Perl 5, a bare block is deemed to be a do-once loop. In Perl 6,
the bare block is not a do-once. Instead C<do {...}> is the do-once
loop (which is another reason you can't put a statement
modifier on it; use C<repeat> for a test-at-the-end loop).
For any statement, prefixing with a C<do> allows you to
return the value of that statement and use it in an expression:
$x = do if $a { $b } else { $c };
This construct only allows you to attach a single statement to the end
of an expression. If you want to continue the expression after the
statement, or if you want to attach multiple statements, you must either
use the curly form or surround the entire expression in brackets of some sort:
@primesquares = (do $_ if prime($_) for 1..100) »**» 2;
Since a bare expression may be used as a statement, you may use C<do>
on an expression, but its only effect is to function as an unmatched
left parenthesis, much like the C<$> operator in Haskell. That is,
precedence decisions do not cross a C<do> boundary, and the missing
"right paren" is assumed at the next statement terminator or unmatched
bracket. A C<do> is unnecessary immediately after any opening bracket as
the syntax inside brackets is a semicolon-separated list of statements,
so the above can in fact be written:
@primesquares = ($_ if prime($_) for 1..100) »**» 2;
This basically gives us list comprehensions as rvalue expressions:
(for 1..100 { $_ if prime($_)}).say
Another consequence of this is that any block just inside a
left parenthesis is immediately called like a bare block, so a
multidimensional list comprehension may be written using a block with
multiple parameters fed by a C<for> modifier:
@names = (-> $name, $num { "$name.$num" } for 'a'..'zzz' X 1..100);
or equivalently, using placeholders:
@names = ({ "$^name.$^num" } for 'a'..'zzz' X 1..100);
Since C<do> is defined as going in front of a statement, it follows
that it can always be followed by a statement label. This is particularly
useful for the do-once block, since it is officially a loop and can take
therefore loop control statements.
=head2 Statement-level bare blocks
Although a bare block occurring as a single statement is no longer
a do-once loop, it still executes immediately as in Perl 5, as if it
were immediately dereferenced with a C<.()> postfix, so within such a
block C<CALLER::> refers to the dynamic scope associated
with the lexical scope surrounding the block.
If you wish to return a closure from a function, you must use an
explicit prefix such as C<return> or C<sub> or C<< -> >>.
sub f1
{
# lots of stuff ...
{ say "I'm a closure." }
}
my $x1= f1; # fall-off return is result of the say, not the closure.
sub f2
{
# lots of stuff ...
return { say "I'm a closure." }
}
my $x2= f2; # returns a Block object.
Use of a placeholder parameter in statement-level blocks triggers a
syntax error, because the parameter is not out front where it can be
seen. However, it's not an error when prefixed by a C<do>, or when
followed by a statement modifier:
# Syntax error: Statement-level placeholder block
{ say $^x };
# Not a syntax error, though $x doesn't get the argument it wants
do { say $^x };
# Not an error: Equivalent to "for 1..10 -> $x { say $x }"
{ say $^x } for 1..10;
# Not an error: Equivalent to "if foo() -> $x { say $x }"
{ say $^x } if foo();
=head2 The C<gather> statement prefix
X<gather>X<take>
A variant of C<do> is C<gather>. Like C<do>, it is followed by a statement
or block, and executes it once. Unlike C<do>, it evaluates the statement or
block in sink (void) context; its return value is instead specified by calling
the C<take> list prefix operator one or more times within the scope (either lexical or dynamic) of
the C<gather>. The C<take> function's signature is like that of C<return>;
while having the syntax of a list operator, it merely returns a single item
or "argument" (see L<S02> for definition).
The C<take> function is lexotic if there is a visible outer C<gather>,
but falls back to purely dynamic if not. Well, it doesn't really
fall back, since a C<take> knows at compile time whether it is being
used lexically or dynamically. Less obviously, so does a C<gather>;
if a C<gather> lexically contains any C<take> calls, it is marked as
lexotic-only, and it will be invisible to a dynamic C<take>. If the
C<gather> contains no C<take> lexically, it by definition cannot be
the lexotic target of any C<take>, so it can only harvest dynamic
C<take> calls. The only remaining difficulty arises if both the user
and a library writer attempt to use dynamic gather with user-defined
callbacks that contain C<take>. So we will say that it is erroneous
for a library writer to mix dynamic gather with callbacks unless
those callbacks are somehow "ungathered" to the outer dynamic scope.
[Conjecture: there should either be an C<callergather> primitive that
does this, or it should be added to the job description of C<lift>.
A third option is to allow labeled C<gather>/C<take> for such a situation,
and dynamic C<take> must match the C<gather>'s label (or lack thereof) exactly.
(Using the term "label" loosely, to include other solutions besides the label syntax,
such as .gather and .take methods on some identity object.)]
If you take multiple items in a comma list (since it is, after all, a list
operator), they will be wrapped up in a C<Parcel> object for return as the
next argument. No additional context is applied by the C<take> operator,
since all context is lazy in Perl 6. The flattening or slicing of any such
returned parcel will be dependent on how the C<gather>'s return iterator is
iterated (with C<.get> vs C<.getarg>).
The value returned by the C<take> to the C<take>'s own context is that same
returned argument (which is ignored when the C<take> is in sink context).
Regardless of the C<take>'s immediate context, the object returned is also
added to the list of values being gathered, which is returned by the C<gather>
as a lazy list (that is, an iterator, really), with each argument element
of that list corresponding to one C<take>.
Any parcels in the returned list are normally flattened when bound
into flat context. When bound into a lol context, however,
the parcel objects become real C<List> objects that keep their
identity as discrete sublists. The eventual binding context thus
determines whether to throw away or keep the groupings resulting from
each individual C<take> call. Most list contexts are flat
rather than sliced, so the boundaries between individual C<take>
calls usually disappear. (FLAT is an acronym meaning Flat Lists Are Typical. :)
Because C<gather> evaluates its block or statement in sink context,
this typically causes the C<take> function to be evaluated in sink
context. However, a C<take> function that is not in sink context
gathers its return objects I<en passant> and also returns them unchanged.
This makes it easy to keep track of what you last "took":
my @uniq = gather for @list {
state $previous = take $_;
next if $_ === $previous;
$previous = take $_;
}
The C<take> function essentially has two contexts simultaneously, the
context in which the C<gather> is operating, and the context in which the
C<take> is operating. These need not be identical contexts, since they
may bind or coerce the resulting parcels differently:
my @y;
@x = gather for 1..2 { # flat context for list of parcels
my ($y) := take $_, $_ * 10; # item context promotes parcel to seq
push @y, $y;
}
# @x contains 4 Ints: 1,10,2,20 flattened by list assignment to @x
# @y contains 2 Seqs: Seq(1,10),Seq(2,20) sliced by binding to positional $y
Likewise, we can just remember the gather's result parcel by binding and
later coercing it:
my |$c := gather for 1..2 {
take $_, $_ * 10;
}
# $c.flat produces 1,10,2,20 -- flatten fully into a list of Ints.
# $c.lol produces Seq(1,10),Seq(2,20) -- list of Seqs, a 2-D list.
# $c.item produces Seq((1,10),(2,20)) -- coerced to Seq of unresolved Parcels
Note that the C<take> itself is in sink context in this example because
the C<for> loop is in the sink context provided inside the gather.
A C<gather> is not considered a loop, but it is easy to combine with a loop
statement as in the examples above.
The C<take> operation may be defined internally using resumable control
exceptions, or dynamic variables, or pigeons carrying clay tablets.
The choice any particular implementation makes is specifically I<not> part
of the definition of Perl 6, and you should not rely on it in portable code.
=head2 The C<lift> statement prefix
X<lift>
When writing generic multi routines you often want to write a bit of
code whose meaning is dependent on the linguistic context of the caller. It's
somewhat like virtual methods where the actual call depends on the type
of the invocant, but here the "invocant" is really the lexical scope of
the caller, and the virtual calls are name bindings. Within a lift,
special rules apply to how names are looked up. Only names defined
in the lexical scope of the immediately surrounding routine are considered concrete.
All other names (including implicit names of operators) are looked up
in the lexical scope of the caller when we actually know who the caller
is at run time. (Note the caller can vary from call to call!)
This applies to anything that needs to be looked up at compile time, including
names of variables, and named values such as types and subs.
Through this mechanism, a generic multi can redirect execution to
a more specific version, but the candidate list for this redirection
is determined by the caller, not by the lexical scope of the multi,
which can't see the caller's lexical scope except through the CALLER::
pseudo package. For example, Perl forces generic C<eq> to coerce to
string comparison, like this:
proto infix:<eq> (Any $a, Any $b) { lift ~$a eq ~$b } # user's eq, user's ~
multi infix:<eq> (Whatever, Any $b) { -> $a { lift $a eq $b } } # user's eq
multi infix:<eq> (Any $a, Whatever) { -> $b { lift $a eq $b } } # user's eq
multi infix:<eq> (&f:($), Any $b) { -> $a { lift f($a) eq $b } } # user's eq
multi infix:<eq> (Str $a, Str $b) { !Str::leg($a, $b) } # primitive leg, primitive !
Note that in each piece of lifted code there are references to
variables defined in the multi, such as C<$a>, C<$b>, and C<&f>.
These are taken at face value. Everything else within a lift is
assumed to mean something in the caller's linguistic context. (This implies
that there are some errors that would ordinarily be found at
compile time that cannot be found until we know what the caller's
lexical scope looks like at run time. That's okay.)
=head2 Other C<do>-like forms
X<do>
Other similar forms, where a keyword is followed by code to be controlled by it, may also take bare statements,
including C<try>, C<quietly>, C<contend>, C<async>, C<lazy>, and C<sink>. These constructs
establish a dynamic scope without necessarily establishing a lexical
scope. (You can always establish a lexical scope explicitly by using
the block form of argument.) As statement introducers, all these
keywords must be followed by whitespace. (You can say something
like C<try({...})>, but then you are calling the C<try()> function
using function call syntax instead, and since Perl does not supply
such a function, it will be assumed to be a user-defined function.)
For purposes of flow control, none of these forms are considered loops,
but they may easily be applied to a normal loop.
Note that any construct in the statement_prefix category defines
special syntax. If followed by a block it does not parse as a
list operator or even as a prefix unary; it will never look for any
additional expression following the block. In particular,
foo( try {...}, 2, 3 )
calls the C<foo> function with three arguments. And
do {...} + 1
add 1 to the result of the do block. On the other hand, if a
statement_prefix is followed by a non-block statement, all nested
blockless statement_prefixes will terminate at the same statement
ending:
do do do foo(); bar 43;
is parsed as:
do { do { do { foo(); }}}; bar(43);
=head1 Switch statements
X<given>X<when>X<switch>X<case>X<default>
A switch statement is a means of topicalizing, so the switch keyword
is the English topicalizer, C<given>. The keyword for individual
cases is C<when>:
given EXPR {
when EXPR { ... }
when EXPR { ... }
default { ... }
}
The current topic is always aliased to the special variable C<$_>.
The C<given> block is just one way to set the current topic, but
a switch statement can be any block that sets C<$_>, including a
C<for> loop (assuming one of its loop variables is bound to C<$_>)
or the body of a method (if you have declared the invocant as C<$_>).
So switching behavior is actually caused by the C<when> statements in
the block, not by the nature of the block itself. A C<when> statement
implicitly does a "smart match" between the current topic (C<$_>) and
the argument of the C<when>. If the smart match succeeds, C<when>'s
associated block is executed, and the innermost surrounding block
that has C<$_> as one of its formal parameters (either explicit
or implicit) is automatically broken out of. (If that is not the
block you wish to leave, you must use the C<LABEL.leave> method (or some
other control exception such as C<return> or C<next>) to
be more specific, since the compiler may find it difficult to guess
which surrounding construct was intended as the actual topicalizer.)
The value of the inner block is returned as the value of the outer
block.
If the smart match fails, control proceeds the next statement
normally, which may or may not be a C<when> statement. Since C<when>
statements are presumed to be executed in order like normal statements,
it's not required that all the statements in a switch block be C<when>
statements (though it helps the optimizer to have a sequence of
contiguous C<when> statements, because then it can arrange to jump
directly to the first appropriate test that might possibly match.)
The default case:
default {...}
is exactly equivalent to
when * {...}
Because C<when> statements are executed in order, the default must
come last. You don't have to use an explicit default--you can just
fall off the last C<when> into ordinary code. But use of a C<default>
block is good documentation.
If you use a C<for> loop with a parameter named C<$_> (either
explicitly or implicitly), that parameter can function as the topic
of any C<when> statements within the loop.
You can explicitly break out of a C<when> block (and its surrounding
topicalizer block) early using the C<succeed> verb. More precisely,
it first scans outward (lexically) for the innermost containing
C<when> block. From there it continues to scan outward to find the
innermost block outside the C<when> that defines C<$_>,
either explicitly or implicitly. (Note that
both of these scans are done at compile time; if the scans fail,
it's a compile-time semantic error.) Typically, such an outer
block will be the block of a C<given> or a C<for> statement, but any block that
sets the topic can be broken out of. At run time,
C<succeed> uses a control exception to scan up the dynamic chain to
find the call frame belonging to that same outer block, and
when it has found that frame, it does a C<.leave> on it to unwind
the call frames. If any arguments are supplied to the C<succeed> function,
they are passed out via the C<leave> method. Since leaving a block is
considered a successful return, breaking out of one with C<succeed> is also considered
a successful return for the purposes of C<KEEP> and C<UNDO>.
The implicit break of a normal
C<when> block works the same way, returning the value of the entire
block (normally from its last statement) via an implicit C<succeed>.
You can explicitly leave a C<when> block and go to the next statement
following the C<when> by using C<proceed>. (Note that, unlike C's
idea of "falling through", subsequent C<when> conditions are evaluated.
To jump into the next C<when> block without testing its condition,
you must use a C<goto>. But generally that means you should refactor
instead.)
If you have a switch that is the main block of a C<for> loop that uses C<$_> as its loop variable, and
you break out of the switch either implicitly or explicitly (that is,
the switch "succeeds"), control merely goes to the end of that block,
and thence on to the next iteration of the loop. You must use C<last>
(or some more violent control exception such as C<return>) to break
out of the entire loop early. Of course, an explicit C<next> might
be clearer than a C<succeed> if you really want to go directly to the
next iteration. On the other hand, C<succeed> can take an optional
argument giving the value for that iteration of the loop. As with
the C<.leave> method, there is also a C<.succeed> method to break from a
labelled block functioning as a switch:
OUTER.succeed($retval)
There is a C<when> statement modifier, but it does not have any
breakout semantics; it is merely a smartmatch against
the current topic. That is,
doit() when 42;
is exactly equivalent to
doit() if $_ ~~ 42;
This is particularly useful for list comprehensions:
@lucky = ($_ when /7/ for 1..100);
=head1 Exception handlers
X<CATCH>
Unlike many other languages, Perl 6 specifies exception handlers by
placing a C<CATCH> block I<within> that block that is having its exceptions
handled.
The Perl 6 equivalent to Perl 5's C<eval {...}> is C<try {...}>.
(Perl 6's C<eval> function only evaluates strings, not blocks, and
does not catch exceptions.)
A C<try> block by default has a C<CATCH> block that handles all fatal
exceptions by ignoring them. If you define a C<CATCH> block within
the C<try>, it replaces the default C<CATCH>. It also makes the C<try>