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 vio‐
31       lates this, but resist the urge.)  Variables that mediate between an
32       outer statement and an inner block (such as loop variables) should gen‐
33       erally be declared as formal parameters to that block.  There are three
34       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 π  = 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 hypo‐
87       thetical value.  It works exactly like "temp", except that the value
88       will be restored only if the current block exits unsuccessfully.  (See
89       Definition of Success below for more.)  "temp" and "let" temporize or
90       hypotheticalize the value or the variable depending on whether you do
91       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 state‐
96       ment can occur there.  That is, these two statements are equivalent:
97
98           my $x = sub { 3 }
99           my $x = sub { 3 };
100
101       End-of-statement cannot occur within a bracketed expression, so this
102       still works:
103
104           my $x = [
105               sub { 3 },  # this comma is not optional
106               sub { 3 }   # the statement won't terminate here
107           ];
108
109       Because subroutine declarations are expressions, not statements, this
110       is now invalid:
111
112           sub f { 3 } sub g { 3 }     # two terms occur in a row
113
114       But these two are valid:
115
116           sub f { 3 }; sub g { 3 };
117           sub f { 3 }; sub g { 3 }    # the trailing semicolon is optional
118

Conditional statements

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

Loop statements

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

The general loop statement

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

The "for" statement

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

The do-once loop

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

Switch statements

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

Exception handlers

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

Control Exceptions

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

The goto statement

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

Exceptions

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

Closure traits

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

Statement parsing

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

Smart matching

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

Definition of Success

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

When is a closure not a closure

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