1Perl6::Bible::S04(3)  User Contributed Perl Documentation Perl6::Bible::S04(3)
2
3
4

NAME

6       Synopsis_04 - Blocks and Statements
7

AUTHOR

9       Larry Wall <larry@wall.org>
10

VERSION

12         Maintainer: Larry Wall <larry@wall.org>
13         Date: 19 Aug 2004
14         Last Modified: 25 Feb 2006
15         Number: 4
16         Version: 10
17
18       This document summarizes Apocalypse 4, which covers the block and
19       statement syntax of Perl.
20

The Relationship of Blocks and Declarations

22       Every block is a closure.  (That is, in the abstract, they're all
23       anonymous subroutines that take a snapshot of their lexical scope.)
24       How any block is invoked and how its results are used is a matter of
25       context, but closures all work the same on the inside.
26
27       Blocks are delimited by curlies, or by the beginning and end of the
28       current compilation unit (either the current file or the current "eval"
29       string).  Unlike in Perl 5, there are (by policy) no implicit blocks
30       around standard control structures.  (You could write a macro that
31       violates this, but resist the urge.)  Variables that mediate between an
32       outer statement and an inner block (such as loop variables) should
33       generally be declared as formal parameters to that block.  There are
34       three ways to declare formal parameters to a closure.
35
36           $func = sub ($a, $b) { print if $a eq $b };  # standard sub declaration
37           $func = -> $a, $b { print if $a eq $b };     # a "pointy" sub
38           $func = { print if $^a eq $^b }              # placeholder arguments
39
40       A bare closure without placeholder arguments that uses $_ (either
41       explicitly or implicitly) is treated as though $_ were a a formal
42       parameter:
43
44           $func = { print if $_ };   # Same as: $func = -> $_ { print if $_ };
45           $func("printme");
46
47       In any case, all formal parameters are the equivalent of "my" variables
48       within the block.  See S06 for more on function parameters.
49
50       Except for such formal parameter declarations, all lexically scoped
51       declarations are visible from the point of declaration to the end of
52       the enclosing block.  Period.  Lexicals may not "leak" from a block to
53       any other external scope (at least, not without some explicit aliasing
54       action on the part of the block, such as exportation of a symbol from a
55       module).  The "point of declaration" is the moment the compiler sees
56       ""my $foo"", not the end of the statement as in Perl 5, so
57
58           my $x = $x;
59
60       will no longer see the value of the outer $x; you'll need to say
61
62           my $x = $OUTER::x;
63
64       instead.  (It's illegal to declare $x twice in the same scope.)
65
66       As in Perl 5, ""our $foo"" introduces a lexically scoped alias for a
67       variable in the current package.
68
69       The new "constant" declarator introduces a lexically scoped name for a
70       compile-time constant, either a variable or a 0-ary sub, which may be
71       initialized with either a pseudo-assignment or a block:
72
73           constant Num $pi = 3;
74           constant Num PI { 3 }
75           constant Num X  = atan(2,2) * 4;
76
77       In any case the initializing value is evaluated at BEGIN time.
78
79       There is a new "state" declarator that introduces a lexically scoped
80       variable like "my" does, but with a lifetime that persists for the life
81       of the closure, so that it keeps its value from the end of one call to
82       the beginning of the next.  Separate clones of the closure get separate
83       state variables.
84
85       Perl 5's ""local"" function has been renamed to "temp" to better
86       reflect what it does.  There is also a "let" function that sets a
87       hypothetical value.  It works exactly like "temp", except that the
88       value will be restored only if the current block exits unsuccessfully.
89       (See Definition of Success below for more.)  "temp" and "let" temporize
90       or hypotheticalize the value or the variable depending on whether you
91       do assignment or binding.
92

Statement-ending blocks

94       A line ending with a closing brace ""}"", followed by nothing but
95       whitespace or comments, will terminates statement if an end of
96       statement can occur there.  That is, these two statements are
97       equivalent:
98
99           my $x = sub { 3 }
100           my $x = sub { 3 };
101
102       End-of-statement cannot occur within a bracketed expression, so this
103       still works:
104
105           my $x = [
106               sub { 3 },  # this comma is not optional
107               sub { 3 }   # the statement won't terminate here
108           ];
109
110       Because subroutine declarations are expressions, not statements, this
111       is now invalid:
112
113           sub f { 3 } sub g { 3 }     # two terms occur in a row
114
115       But these two are valid:
116
117           sub f { 3 }; sub g { 3 };
118           sub f { 3 }; sub g { 3 }    # the trailing semicolon is optional
119

Conditional statements

121       The "if" and "unless" statements work almost exactly as they do in Perl
122       5, except that you may omit the parentheses on the conditional:
123
124           if $foo == 123 {
125               ...
126           }
127           elsif $foo == 321 {
128               ...
129           }
130           else {
131               ...
132           }
133
134       Conditional statement modifiers also work as in Perl 5.  So do the
135       implicit conditionals implied by short-circuit operators.  And there's
136       a new "elsunless" in Perl 6--except that you have to spell it "elsif
137       not".  ":-)"
138

Loop statements

140       The "while" and "until" statements work as in Perl 5, except that you
141       may leave out the parentheses around the conditional:
142
143           while $bar < 100 {
144               ...
145           }
146
147       Looping statement modifiers are the same as in Perl 5, except that to
148       avoid confusion applying one to a "do" block is specifically
149       disallowed.  Instead of
150
151           do {
152               ...
153           } while $x;
154
155       you should write
156
157           loop {
158               ...
159           } while $x;
160
161       Loop modifiers "next", "last", and "redo" work as in Perl 5.
162
163       There is no longer a "continue" block.  Instead, use a "NEXT" block
164       within the loop.  See below.
165

The general loop statement

167       The "loop" statement is the C-style "for" loop in disguise:
168
169           loop ($i = 0; $i < 10; $i++) {
170               ...
171           }
172
173       As seen in the previous section, the 3-part loop spec may be entirely
174       omitted to write an infinite loop.  If you omit the 3-part loop spec
175       you may add a "while" or "until" statement modifier at the end to make
176       it a "repeat at least once" loop.  Unlike "do" in Perl 5, it's a real
177       loop block, so you may use loop modifiers.
178

The "for" statement

180       There is no "foreach" statement any more. It's always spelled "for" in
181       Perl 6, so it always takes a list as an argument:
182
183           for @foo { print }
184
185       As mentioned earlier, the loop variable is named by passing a parameter
186       to the closure:
187
188           for @foo -> $item { print $item }
189
190       Multiple parameters may be passed, in which case the list is traversed
191       more than one element at a time:
192
193           for %hash.kv -> $key, $value { print "$key => $value\n" }
194
195       To process two arrays in parallel, use the "each" function:
196
197           for each(@a;@b) -> $a, $b { print "[$a, $b]\n" }
198
199       or use the "zip" function to generate a list of tuples that each can be
200       bound to multiple arguments enclosed in square brackets:
201
202           for zip(@a;@b) -> [$a, $b] { print "[$a, $b]\n" }
203
204       The list is evaluated lazily by default, so instead of using a "while"
205       to read a file a line at a time as you would in Perl 5:
206
207           while (my $line = <STDIN>) {...}
208
209       in Perl 6 you should use a "for" (plus a unary "=" "iterate the
210       iterator" operator) instead:
211
212           for =$*IN -> $line {...}
213
214       This has the added benefit of limiting the scope of the $line parameter
215       to the block it's bound to.  (The "while"'s declaration of $line
216       continues to be visible past the end of the block.  Remember, no
217       implicit block scopes.)  It is also possible to write
218
219           while =$*IN -> $line {...}
220
221       Note also that Perl 5's special rule causing
222
223           while (<>) {...}
224
225       to automatically assign to $_ is not carried over to Perl 6.  That
226       should now be written:
227
228           for =<> {...}
229
230       which is short for
231
232           for =$*ARGS {...}
233
234       Parameters are by default readonly within the block.  You can declare a
235       parameter read/write by including the ""is rw"" trait.  If you rely on
236       $_ as the implicit parameter to a block, then $_ is considered
237       read/write by default.  That is, the construct:
238
239           for @foo {...}
240
241       is actually short for:
242
243           for @foo -> $_ is rw {...}
244
245       so you can modify the current list element in that case.  However, any
246       time you specify the arguments, they default to read only.
247
248       When used as statement modifers, "for" and "given" use a private
249       instance of $_ for the left side of the statement.  The outer $_ can be
250       referred to as $OUTER::_.  (And yes, this implies that the compiler may
251       have to retroactively change the binding of <$_> on the left side.  But
252       it's what people expect of a pronoun like "it".)
253

The do-once loop

255       In Perl 5, a bare block is deemed to be a do-once loop.  In Perl 6, the
256       bare block is not a do-once.  Instead "do {...}" is the do-once loop
257       (which is another reason you can't put a "while" or "until" modifier on
258       it).
259
260       For any statement, prefixing with a "do" allows you to return the value
261       of that statement and use it in an expression:
262
263           $x = do if $a { $b } else { $c };
264
265       This construct only allows you to prefix a statement.  If you want to
266       continue the expression after the statement you must use the curly
267       form.
268
269       Since "do" is defined as going in front of a statement, it follows that
270       it can always be followed by a statement label.  This is particularly
271       useful for the do-once block, since it is offically a loop and can take
272       therefore loop control statements.
273

Switch statements

275       A switch statement is a means of topicalizing, so the switch keyword is
276       the English topicalizer, "given".  The keyword for individual cases is
277       "when":
278
279           given EXPR {
280               when EXPR { ... }
281               when EXPR { ... }
282               default { ... }
283           }
284
285       The current topic is always aliased to the special variable $_.  The
286       "given" block is just one way to set the current topic, but a switch
287       statement can be any block that sets $_, including a "for" loop (in
288       which the first loop parameter is the topic) or the body of a method
289       (if you have declared the invocant as $_).  So switching behavior is
290       actually caused by the "when" statements in the block, not by the
291       nature of the block itself.  A "when" statement implicitly does a
292       "smart match" between the current topic ($_) and the argument of the
293       "when".  If the smart match succeeds, the associated closure is
294       executed, and the surrounding block is automatically broken out of.  If
295       the smart match fails, control passes to the next statement normally,
296       which may or may not be a "when" statement.  Since "when" statements
297       are presumed to be executed in order like normal statements, it's not
298       required that all the statements in a switch block be "when" statements
299       (though it helps the optimizer to have a sequence of contiguous "when"
300       statements, because then it can arrange to jump directly to the first
301       appropriate test that might possibly match.)
302
303       The default case:
304
305           default {...}
306
307       is exactly equivalent to
308
309           when true {...}
310
311       Because "when" statements are executed in order, the default must come
312       last.  You don't have to use an explicit default--you can just fall off
313       the last "when" into ordinary code.  But use of a "default" block is
314       good documentation.
315
316       If you use a "for" loop with a named parameter, the parameter is also
317       aliased to $_ so that it can function as the topic of any "when"
318       statements within the loop.  If you use a "for" statement with multiple
319       parameters, only the first parameter is aliased to $_ as the topic.
320
321       You can explicitly break out of a "when" block (and its surrounding
322       switch) early using the "break" verb.  You can explicitly break out of
323       a "when" block and go to the next statement by using "continue".  (Note
324       that, unlike C's idea of falling through, subsequent "when" conditions
325       are evaluated.  To jump into the next "when" block you must use a
326       "goto".)
327
328       If you have a switch that is the main block of a "for" loop, and you
329       break out of the switch either implicitly or explicitly, it merely goes
330       to the next iteration of the loop.  You must use "last" to break out of
331       the entire loop early.  Of course, an explicit "next" would be clearer
332       than a "break" if you really want to go to the next iteration.
333       Possibly we'll outlaw "break" in a loop topicalizer.
334

Exception handlers

336       Unlike many other languages, Perl 6 specifies exception handlers by
337       placing a "CATCH" block within that block that is having its exceptions
338       handled.
339
340       The Perl 6 equivalent to Perl 5's "eval {...}" is "try {...}".  (Perl
341       6's "eval" function only evaluates strings, not blocks.)  A "try" block
342       by default has a "CATCH" block that handles all exceptions by ignoring
343       them.  If you define a "CATCH" block within the "try", it replaces the
344       default "CATCH".  It also makes the "try" keyword redundant, because
345       any block can function as a "try" block if you put a "CATCH" block
346       within it.
347
348       An exception handler is just a switch statement on an implicit topic
349       supplied within the "CATCH" block.  That implicit topic is the current
350       exception object, also known as $!.  Inside the "CATCH" block, it's
351       also bound to $_, since it's the topic.  Because of smart matching,
352       ordinary "when" statements are sufficiently powerful to pattern match
353       the current exception against classes or patterns or numbers without
354       any special syntax for exception handlers.  If none of the cases in the
355       "CATCH" handles the exception, the exception is rethrown.  To ignore
356       all unhandled exceptions, use an empty "default" case.  (In other
357       words, there is an implicit "die $!" just inside the end of the "CATCH"
358       block.  Handled exceptions break out past this implicit rethrow.)
359

Control Exceptions

361       All abnormal control flow is, in the general case, handled by the
362       exception mechanism (which is likely to be optimized away in specific
363       cases.)  Here "abnormal" means any transfer of control outward that is
364       not just falling off the end of a block.  A "return", for example, is
365       considered a form of abnormal control flow, since it can jump out of
366       multiple levels of closure to the end of the scope of the current
367       subroutine definition.  Loop commands like "next" are abnormal, but
368       looping because you hit the end of the block is not.  The implicit
369       break of a "when" block is abnormal.
370
371       A "CATCH" block handles only "bad" exceptions, and lets control
372       exceptions pass unhindered.  Control exceptions may be caught with a
373       "CONTROL" block.  Generally you don't need to worry about this unless
374       you're defining a control construct.  You may have one "CATCH" block
375       and one "CONTROL" block, since some user-defined constructs may wish to
376       supply an implicit "CONTROL" block to your closure, but let you define
377       your own "CATCH" block.
378
379       A "return" always exits from the lexically surrounding sub or method
380       definition (that is, from a function officially declared with the
381       "sub", "method", or "submethod" keywords).  Pointy subs and bare
382       closures are transparent to "return".  If you pass a reference to a
383       closure outside of its official "sub" scope, it is illegal to return
384       from it.  You may only leave the closure block itself with "leave" or
385       by falling off the end of it.
386
387       To return a value from a pointy sub or bare closure, you either just
388       let the block return the value of its final expression, or you can use
389       "leave".  A "leave" by default exits from the innermost block.  But you
390       may change the behavior of "leave" with selector adverbs:
391
392           leave :from(Loop) :label<LINE> <== 1,2,3;   # XXX "with"?
393
394       The innermost block matching the selection criteria will be exited.
395       The return value, if any, must be passed as a list.  To return pairs as
396       part of the value, you can use a pipe:
397
398           leave <== :foo:bar:baz(1) if $leaving;
399
400       or going the other way::
401
402           $leaving and :foo:bar:baz(1) ==> leave;
403
404       In theory, any user-defined control construct can catch any control
405       exception it likes.  However, there have to be some culturally enforced
406       standards on which constructs capture which exceptions.  Much like
407       "return" may only return from an "official" subroutine or method, a
408       loop exit like "next" should be caught by the construct the user
409       expects it to be caught by.  In particular, if the user labels a loop
410       with a specific label, and calls a loop control from within the lexical
411       scope of that loop, and if that call mentions the outer loop's label,
412       then that outer loop is the one that must be controlled. (This search
413       of lexical scopes is limited to the current "official" subroutine.)  If
414       there is no such lexically scoped outer loop in current subroutine.
415       Then a fallback search is made outward through the dynamic scopes in
416       the same way Perl 5 does.  (The difference between Perl 5 and Perl 6 in
417       this respect arises only because Perl 5 didn't have user-defined
418       control structures, hence the sub's lexical scope was always the
419       innermost dynamic scope, so the preference to the lexical scope in the
420       current sub was implicit.  For Perl 6 we have to make this preference
421       explicit.)
422

The goto statement

424       In addition to "next", "last", and "redo", Perl 6 also supports "goto".
425       As with ordinary loop controls, the label is searched for first
426       lexically within the current subroutine, then dynamically outside of
427       it.  Unlike with loop controls, however, scanning a scope includes a
428       scan of any lexical scopes included within the current candidate scope.
429       As in Perl 5, it is possible to "goto" into a lexical scope, but only
430       for lexical scopes that require no special initialization of
431       parameters.  (Initialization of ordinary variables does not
432       count--presumably the presence of a label will prevent code-movement
433       optimizations past the label.)  So, for instance, it's always possible
434       to goto into the next case of a "when" or into either the "then" or
435       "else" branch of a conditional.  You may not go into a "given" or a
436       "for", though, because that would bypass a formal parameter binding
437       (not to mention list generation in the case of "for").  (Note: the
438       implicit default binding of an outer $_ to an inner $_ can be emulated
439       for a bare block, so that doesn't fall under the prohibition on
440       bypassing formal binding.)
441

Exceptions

443       As in Perl 5, many built-in functions simply return undef when you ask
444       for a value out of range, or the function fails somehow.  Unlike in
445       Perl 5, these may be "interesting" values of undef that contain
446       information about the error.  If you try to use an undefined value,
447       that information can then be conveyed to the user.  In essence, undef
448       can be an unthrown exception object that just happens to return 0 when
449       you ask it whether it's defined or it's true.  Since $! contains the
450       current error code, saying "die $!" will turn an unthrown exception
451       into a thrown exception.  (A bare "die" does the same.)
452
453       You can cause built-ins to automatically throw exceptions on failure
454       using
455
456           use fatal;
457
458       The "fail" function responds to the caller's "use fatal" state.  It
459       either returns an unthrown exception, or throws the exception.
460
461       If an exception is raised while $! already contains an exception that
462       is active and "unhandled", no information is discarded.  The old
463       exception is pushed onto the exception stack within the new exception,
464       which is then bound to $! and, hopefully, propagated.  The default
465       printout for the new exception should include the old exception
466       information so that the user can trace back to the original error.
467       (Likewise, rethrown exceptions add information about how the exception
468       is propagated.)  The exception stack within $! is available as $![].
469
470       Exception objects are born "unhandled".  The $! object keeps track of
471       whether it's currently "handled" or "unhandled".  The exception in $!
472       still exists after it has been caught, but catching it marks it as
473       handled if any of the cases in the switch matched.  Handled exceptions
474       don't require their information to be preserved if another exception
475       occurs.
476

Closure traits

478       A "CATCH" block is just a trait of the closure containing it.  Other
479       blocks can be installed as traits as well.  These other blocks are
480       called at various times, and some of them respond to various control
481       exceptions and exit values:
482
483             BEGIN {...}*      at compile time, ASAP
484             CHECK {...}*      at compile time, ALAP
485              INIT {...}*      at run time, ASAP
486               END {...}       at run time, ALAP
487             FIRST {...}*      at first block entry time
488             ENTER {...}*      at every block entry time
489             LEAVE {...}       at every block exit time
490              KEEP {...}       at every successful block exit
491              UNDO {...}       at every unsuccessful block exit
492              NEXT {...}       at loop continuation time
493              LAST {...}       at loop termination time
494               PRE {...}       assert precondition at every block entry
495              POST {...}       assert postcondition at every block exit
496             CATCH {...}       catch exceptions
497           CONTROL {...}       catch control exceptions
498
499       Those marked with a "*" can also be used within an expression:
500
501           my $compiletime = BEGIN { localtime };
502           our $temphandle = FIRST { maketemp() };
503
504       Code that is generated at run time can still fire off "CHECK" and
505       "INIT" blocks, though of course those blocks can't do things that would
506       require travel back in time.
507
508       Some of these also have corresponding traits that can be set on
509       variables.  These have the advantage of passing the variable in
510       question into the closure as its topic:
511
512           my $r will first { .set_random_seed() };
513           our $h will enter { .rememberit() } will undo { .forgetit() };
514
515       Apart from "CATCH" and "CONTROL", which can only occur once, most of
516       these can occur multiple times within the block.  So they aren't really
517       traits, exactly--they add themselves onto a list stored in the actual
518       trait.  So if you examine the "ENTER" trait of a block, you'll find
519       that it's really a list of closures rather than a single closure.
520
521       The semantics of "INIT" and "FIRST" are not equivalent to each other in
522       the case of cloned closures.  An "INIT" only runs once for all copies
523       of a cloned closure.  A "FIRST" runs separately for each clone, so
524       separate clones can keep separate state variables:
525
526           our $i = 0;
527           ...
528           $func = { state $x will first{$i++}; dostuff($i) };
529
530       But "state" automatically applies "first" semantics to any initializer,
531       so this also works:
532
533           $func = { state $x = $i++; dostuff($i) }
534
535       Each subsequent clone gets an initial state that is one higher than the
536       previous, and each clone maintains its own state of $x, because that's
537       what "state" variables do.
538
539       All of these trait blocks can see any previously declared lexical
540       variables, even if those variables have not been elaborated yet when
541       the closure is invoked.  (In which case the variables evaluate to an
542       undefined value.)
543
544       Note: Apocalypse 4 confused the notions of "PRE"/"POST" with
545       "ENTER"/"LEAVE".  These are now separate notions.  "ENTER" and "LEAVE"
546       are used only for their side effects.  "PRE" and "POST" must return
547       boolean values that are evaluated according to the usual Design by
548       Contract rules.  (Plus, if you use "ENTER"/"LEAVE" in a class block,
549       they only execute when the class block is executed, but "PRE"/"POST" in
550       a class block are evaluated around every method in the class.)
551
552       "LEAVE" blocks are evaluated after "CATCH" and "CONTROL" blocks,
553       including the "LEAVE" variants, "KEEP" and "UNDO".  "POST" blocks are
554       evaluated after everything else, to guarantee that even "LEAVE" blocks
555       can't violate DBC.  Likewise "PRE" blocks fire off before any "ENTER"
556       or "FIRST" (though not before "BEGIN", "CHECK", or "INIT", since those
557       are done at compile or process initialization time).
558

Statement parsing

560       In this statement:
561
562           given EXPR {
563               when EXPR { ... }
564               when EXPR { ... }
565               ...
566           }
567
568       parentheses aren't necessary around "EXPR" because the whitespace
569       between "EXPR" and the block forces the block to be considered a block
570       rather than a subscript.  This works for all control structures, not
571       just the new ones in Perl 6.  A bare block where an operator is
572       expected is always considered a statement block if there's space before
573       it:
574
575           if $foo { ... }
576           elsif $bar { ... }
577           else { ... }
578           while $more { ... }
579           for 1..10 { ... }
580
581       (You can still parenthesize the expression argument for old times'
582       sake, as long as there's a space between the closing paren and the
583       opening brace.)
584
585       On the other hand, anywhere a term is expected, a block is taken to be
586       a closure definition (an anonymous subroutine).  If the closure appears
587       to delimit nothing but a comma-separated list starting with a pair
588       (counting a single pair as a list of one element), the closure will be
589       immediately executed as a hash composer.
590
591           $hashref = { "a" => 1 };
592           $hashref = { "a" => 1, $b, $c, %stuff, @nonsense };
593
594           $coderef = { "a", 1 };
595           $coderef = { "a" => 1, $b, $c ==> print };
596
597       If you wish to be less ambiguous, the "hash" list operator will
598       explicitly evaluate a list and compose a hash of the returned value,
599       while "sub" introduces an anonymous subroutine:
600
601           $coderef = sub { "a" => 1 };
602           $hashref = hash("a" => 1);
603           $hashref = hash("a", 1);
604
605       If a closure is the right argument of the dot operator, the closure is
606       interpreted as a hash subscript, even if there is space before the dot.
607
608           $ref = {$x};        # closure because term expected
609           if $term{$x}        # subscript because operator expected
610           if $term {$x}       # expression followed by statement block
611           if $term .{$x}      # valid subscript (term expected after dot)
612
613       Similar rules apply to array subscripts:
614
615           $ref = [$x];        # array composer because term expected
616           if $term[$x]        # subscript because operator expected
617           if $term [$x]       # syntax error (two terms in a row)
618           if $term .[$x]      # valid subscript (term expected after dot)
619
620       And to the parentheses delimiting function arguments:
621
622           $ref = ($x);        # grouping parens because term expected
623           if $term($x)        # function call because operator expected
624           if $term ($x)       # syntax error (two terms in a row)
625           if $term .($x)      # valid function call (term expected after dot)
626
627       Outside of any kind of expression brackets, a trailing curly on a line
628       by itself (not counting whitespace or comments) always reverts to the
629       precedence of semicolon whether or not you put a semicolon after it.
630       (In the absence of an explicit semicolon, the current statement may
631       continue on a subsequent line, but only with valid statement
632       continuators such as "else".  A modifier on a "loop" statement must
633       continue on the same line, however.)
634
635       Final blocks on statement-level constructs always imply semicolon
636       precedence afterwards regardless of the position of the closing curly.
637       Statement-level constructs are distinguished in the grammar by being
638       declared in the statement syntactic group:
639
640           macro statement_control:<if> ($expr, &ifblock) {...}
641           macro statement_control:<while> ($expr, &whileblock) {...}
642           macro statement_control:<BEGIN> (&beginblock) {...}
643
644       Statement-level constructs may start only where the parser is expecting
645       the start of a statement.  To embed a statement in an expression you
646       must use something like "do {...}" or "try {...}".
647
648           $x =  do { given $foo { when 1 {2} when 3 {4} } + $bar;
649           $x = try { given $foo { when 1 {2} when 3 {4} } + $bar;
650
651       Just because there's a "statement_control:<BEGIN>" does not preclude us
652       from also defining a "prefix:<BEGIN>" that can be used within an
653       expression:
654
655           macro prefix:<BEGIN> (&beginblock) { beginblock().repr }
656
657       Then you can say things like:
658
659           $recompile_by = BEGIN { time } + $expiration_time;
660
661       But "statement_control:<BEGIN>" hides "prefix:<BEGIN>" at the start of
662       a statement.  You could also conceivably define a "prefix:<if>", but
663       then you would get a syntax error when you say:
664
665           print if $foo
666
667       since "prefix:<if>" would hide "statement_modifier:<if>".
668

Smart matching

670       Here is the current table of smart matches (which probably belongs in
671       S03).  The list is intended to reflect forms that can be recognized at
672       compile time.  If none of these forms is recognized at compile time, it
673       falls through to do MMD to "infix:<~~>()", which presumably reflects
674       similar semantics, but can finesse things that aren't exact type
675       matches.  Note that all types are scalarized here.  Both "~~" and
676       "given"/"when" provide scalar contexts to their arguments.  (You can
677       always hyperize "~~" explicitly, though.)  So both $_ and $x here are
678       potentially references to container objects.  And since lists promote
679       to arrays in scalar context, there need be no separate entries for
680       lists.
681
682           $_      $x        Type of Match Implied    Matching Code
683           ======  =====     =====================    =============
684           Any     Code<$>   scalar sub truth         match if $x($_)
685           Hash    Hash      hash keys identical      match if $_.keys.sort XeqX $x.keys.sort
686           Hash    any(Hash) hash key intersection    match if $_{any(Hash.keys)}
687           Hash    Array     hash value slice truth   match if $_{any(@$x)}
688           Hash    any(list) hash key slice existence match if exists $_{any(list)}
689           Hash    all(list) hash key slice existence match if exists $_{all(list)}
690           Hash    Rule      hash key grep            match if any($_.keys) ~~ /$x/
691           Hash    Any       hash entry existence     match if exists $_{$x}
692           Hash    .{Any}    hash element truth*      match if $_{Any}
693           Hash    .<string> hash element truth*      match if $_<string>
694           Array   Array     arrays are identical     match if $_ X~~X $x
695           Array   any(list) list intersection        match if any(@$_) ~~ any(list)
696           Array   Rule      array grep               match if any(@$_) ~~ /$x/
697           Array   Num       array contains number    match if any($_) == $x
698           Array   Str       array contains string    match if any($_) eq $x
699           Array   .[number] array element truth*     match if $_[number]
700           Num     NumRange  in numeric range         match if $min <= $_ <= $max
701           Str     StrRange  in string range          match if $min le $_ le $max
702           Any     Code<>    simple closure truth*    match if $x() (ignoring $_)
703           Any     Class     class membership         match if $_.does($x)
704           Any     Role      role playing             match if $_.does($x)
705           Any     Num       numeric equality         match if $_ == $x
706           Any     Str       string equality          match if $_ eq $x
707           Any     .method   method truth*            match if $_.method
708           Any     Rule      pattern match            match if $_ ~~ /$x/
709           Any     subst     substitution match*      match if $_ ~~ subst
710           Any     boolean   simple expression truth* match if true given $_
711           Any     undef     undefined                match unless defined $_
712           Any     Any       run-time dispatch        match if infix:<~~>($_, $x)
713
714       Matches marked with * are non-reversible, typically because "~~" takes
715       its left side as the topic for the right side, and sets the topic to a
716       private instance of $_ for its right side, so $_ means something
717       different on either side.  Such non-reversible constructs can be made
718       reversible by putting the leading term into a closure to defer the
719       binding of $_.  For example:
720
721           $x ~~ .does(Storeable)      # okay
722           .does(Storeable) ~~ $x      # not okay--gets wrong $_ on left
723           { .does(Storeable) } ~~ $x  # okay--closure binds its $_ to $x
724
725       Exactly the same consideration applies to "given" and "when":
726
727           given $x { when .does(Storeable) {...} }      # okay
728           given .does(Storeable) { when $x {...} }      # not okay
729           given { .does(Storeable) } { when $x {...} }  # okay
730
731       Boolean expressions are those known to return a boolean value, such as
732       comparisons, or the unary "?" operator.  They may reference $_
733       explicitly or implicitly.  If they don't reference $_ at all, that's
734       okay too--in that case you're just using the switch structure as a more
735       readable alternative to a string of elsifs.
736
737       The primary use of the "~~" operator is to return a boolean value in a
738       boolean context.  However, for certain operands such as regular
739       expressions, use of the operator within scalar or list context
740       transfers the context to that operand, so that, for instance, a regular
741       expression can return a list of matched substrings, as in Perl 5.  The
742       complete list of such operands is TBD.
743
744       It has not yet been determined if run-time dispatch of "~~" will
745       attempt to emulate the compile-time precedence table before reverting
746       to MMD, or just go directly to MMD.  There are good arguments for both
747       sides, and we can decide when we see more examples of how it'll work
748       out.
749

Definition of Success

751       Hypothetical variables are somewhat transactional--they keep their new
752       values only on successful exit of the current block, and otherwise are
753       rolled back to their original value.
754
755       It is, of course, a failure to leave the block by propagating an error
756       exception, though returning a defined value after catching an exception
757       is okay.
758
759       In the absence of exception propagation, a successful exit is one that
760       returns a defined value in scalar context, or any number of values in
761       list context as long as the length is defined.  (A length of +Inf is
762       considered a defined length.  A length of 0 is also a defined length,
763       which means it's a "successful" return even though the list would
764       evaluate to false in a boolean context.)  A list can have a defined
765       length even if it contains undefined scalar values.  A list is of
766       undefined length only if it contains an undefined generator, which,
767       happily, is what is returned by the "undef" function when used in list
768       context.  So any Perl 6 function can say
769
770           return undef;
771
772       and not care about whether the function is being called in scalar or
773       list context.  To return an explicit scalar undef, you can always say
774
775           return scalar(undef);
776
777       Then in list context, you're returning a list of length 1, which is
778       defined (much like in Perl 5).  But generally you should be using
779       "fail" in such a case to return an exception object.  Exception objects
780       also behave like undefined generators in list context.  In any case,
781       returning an unthrown exception is considered failure from the
782       standpoint of "let".  Backtracking over a closure in a rule is also
783       considered failure of the closure, which is how hypothetical variables
784       are managed by rules.  (And on the flip side, use of "fail" within a
785       rule closure initiates backtracking of the rule.)
786

When is a closure not a closure

788       Everything is conceptually a closure in Perl 6, but the optimizer is
789       free to turn unreferenced closures into mere blocks of code.  It is
790       also free to turn referenced closures into mere anonymous subroutines
791       if the block does not refer to any external lexicals that could
792       themselves be cloned.  In particular, named subroutines in any scope do
793       not consider themselves closures unless you take a reference to them.
794       So
795
796           sub foo {
797               my $x = 1;
798               my sub bar { print $x }         # not cloned yet
799               my &baz = { bar(); print $x };  # cloned immediately
800               my $barref = &bar;              # now bar is cloned
801               return &baz;
802           }
803
804       When we say "clone", we mean the way the system takes a snapshot of the
805       routine's lexical scope and binds it to the current instance of the
806       routine so that if you ever use the current reference to the routine,
807       it gets the current snapshot of its world, lexically speaking.
808
809       Some closures produce references at compile time that cannot be cloned,
810       because they're not attached to any runtime code that can actively
811       clone them.  "BEGIN", "CHECK", "INIT", and "END" blocks probably fall
812       into this category.  Therefore you can't reliably refer to run-time
813       variables from them even if they appear to be in scope.  (The compile-
814       time closure may, in fact, see a some kind of permanent copy of the
815       variable for some storage classes, but the variable is likely to be
816       undefined when the closure is run in any case.)  It's only safe to
817       refer to package variables and file-scoped lexicals from such a
818       routine.
819
820       On the other hand, it is required that "CATCH" and "LEAVE" blocks be
821       able to see transient variables in their current lexical scope, so
822       their cloning status depends at least on the cloning status of the
823       block they're in.
824
825
826
827perl v5.12.0                      2006-02-28              Perl6::Bible::S04(3)
Impressum