Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 1828 lines (1420 sloc) 79.785 kb
be1862e9 » Darren_Duncan
2009-07-05 P6 Synopsis : ws changes - to help BOMers, added leading blank line t…
1
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
2 =encoding utf8
3
4 =head1 TITLE
5
6 Synopsis 4: Blocks and Statements
7
04840a3a » lwall
2009-06-26 [Spec] treat all authors equally
8 =head1 AUTHORS
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
9
04840a3a » lwall
2009-06-26 [Spec] treat all authors equally
10 Larry Wall <larry@wall.org>
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
11
12 =head1 VERSION
13
04840a3a » lwall
2009-06-26 [Spec] treat all authors equally
14 Created: 19 Aug 2004
15
5dfd9966 » TimToady
2012-07-28 resumable failures for coercions
16 Last Modified: 28 Jul 2012
003891a8 » TimToady
2012-07-28 Explication of lazy warnings
17 Version: 118
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
18
19 This document summarizes Apocalypse 4, which covers the block and
20 statement syntax of Perl.
21
f9c9c20c » lwall
2009-11-10 [S04] define "lexotic"
22 =head1 The Relationship of Lexical and Dynamic Scopes
23
24 Control flow is a dynamic feature of all computer programming
25 languages, but languages differ in the extent to which control flow is
26 attached to declarative features of the language, which are often known
27 as "static" or "lexical". We use the phrase "lexical scoping" in its
28 industry-standard meaning to indicate those blocks that surround the
29 current textual location. More abstractly, any declarations associated
30 with those textual blocks are also considered to be part of the lexical
31 scope, and this is where the term earns the "lexical" part of its name,
32 in the sense that lexical scoping actually does define the "lexicon"
33 for the current chunk of code, insofar as the definitions of variables
34 and routines create a local domain-specific language.
35
36 We also use the term "dynamic scoping" in the standard fashion to
37 indicate the nested call frames that are created and destroyed every
38 time a function or method is called. In most interesting programs the
39 dynamic scopes are nested quite differently from the lexical scopes,
40 so it's important to distinguish carefully which kind of scoping
41 we're talking about.
42
dff23644 » lwall
2009-11-20 [Spec] slaughter various confusing overloadings of the term 'context'
43 Further compounding the difficulty is that every dynamic scope's outer call frame is
f9c9c20c » lwall
2009-11-10 [S04] define "lexotic"
44 associated with a lexical scope somewhere, so you can't just consider
45 one kind of scoping or the other in isolation. Many constructs define
46 a particular interplay of lexical and dynamic features. For instance,
dff23644 » lwall
2009-11-20 [Spec] slaughter various confusing overloadings of the term 'context'
47 unlike normal lexically scope variables, dynamic variables search
f9c9c20c » lwall
2009-11-10 [S04] define "lexotic"
48 up the dynamic call stack for a variable of a particular name, but at
49 each "stop" along the way, they are actually looking in the lexical
dff23644 » lwall
2009-11-20 [Spec] slaughter various confusing overloadings of the term 'context'
50 "pad" associated with that particular dynamic scope's call frame.
f9c9c20c » lwall
2009-11-10 [S04] define "lexotic"
51
52 In Perl 6, control flow is designed to do what the user expects most of
53 the time, but this implies that we must consider the declarative nature
54 of labels and blocks and combine those with the dynamic nature of the
55 call stack. For instance, a C<return> statement always returns from
56 the lexically scoped subroutine that surrounds it. But to do that,
57 it may eventually have to peel back any number of layers of dynamic
dff23644 » lwall
2009-11-20 [Spec] slaughter various confusing overloadings of the term 'context'
58 call frames internal to the subroutine's current call frame. The lexical scope supplies the
f9c9c20c » lwall
2009-11-10 [S04] define "lexotic"
59 declared target for the dynamic operation. There does not seem to
60 be a prevailing term in the industry for this, so we've coined the
61 term I<lexotic> to refer to these strange operations that perform a
62 dynamic operation with a lexical target in mind. Lexotic operators
63 in Perl 6 include:
64
65 return
66 next
67 last
68 redo
69 goto
70
71 Some of these operators also fall back to a purely dynamic interpretation
a826b588 » TimToady
2010-09-06 [S04,S32] implicit loops expect to be controlled by bare next and last
72 if the lexotic interpretation doesn't work. For instance, C<next> with a label
f9c9c20c » lwall
2009-11-10 [S04] define "lexotic"
73 will prefer to exit a loop lexotically, but if there is no loop with
74 an appropriate label in the lexical context, it will then scan upward
dff23644 » lwall
2009-11-20 [Spec] slaughter various confusing overloadings of the term 'context'
75 dynamically through the call frames for any loop with the appropriate label, even though that
a826b588 » TimToady
2010-09-06 [S04,S32] implicit loops expect to be controlled by bare next and last
76 loop will not be lexically visible. (C<next> without a label is purely dynamic.) Lexotic and dynamic control flow
f9c9c20c » lwall
2009-11-10 [S04] define "lexotic"
77 is implemented by a system of control exceptions. For the lexotic
78 return of C<next>, the control exception will contain the identity of
79 the loop scope to be exited (since the label was already "used up" to
80 discover that identity), but for the dynamic fallback, the exception
81 will contain only the loop label to be matched dynamically. See
82 L</Control Exceptions> below.
83
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
84 =head1 The Relationship of Blocks and Declarations
85
86 Every block is a closure. (That is, in the abstract, they're all
f9c9c20c » lwall
2009-11-10 [S04] define "lexotic"
87 anonymous subroutines that take a snapshot of their lexical environment.)
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
88 How a block is invoked and how its results are used are matters of
89 context, but closures all work the same on the inside.
90
91 Blocks are delimited by curlies, or by the beginning and end of the
92 current compilation unit (either the current file or the current
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
93 C<eval> string). Unlike in Perl 5, there are (by policy) no implicit
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
94 blocks around standard control structures. (You could write a macro
95 that violates this, but resist the urge.) Variables that mediate
96 between an outer statement and an inner block (such as loop variables)
97 should generally be declared as formal parameters to that block. There
98 are three ways to declare formal parameters to a closure.
99
100 $func = sub ($a, $b) { .print if $a eq $b }; # standard sub declaration
101 $func = -> $a, $b { .print if $a eq $b }; # a "pointy" block
102 $func = { .print if $^a eq $^b } # placeholder arguments
103
71691eb8 » jdlugosz
2009-05-26 [s04] replace example that no longer was applicable after previous ed…
104 A bare closure (except the block associated with a conditional statement)
105 without placeholder arguments that uses C<$_>
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
106 (either explicitly or implicitly) is treated as though C<$_> were a
107 formal parameter:
108
681ca233 » pmichaud
2009-07-28 Fix incorrect specification of implicit $_ in blocks.
109 $func = { .print if $_ }; # Same as: $func = <-> $_ { .print if $_ };
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
110 $func("printme");
111
112 In any case, all formal parameters are the equivalent of C<my> variables
113 within the block. See S06 for more on function parameters.
114
115 Except for such formal parameter declarations, all lexically scoped
116 declarations are visible from the point of declaration to the end of
117 the enclosing block. Period. Lexicals may not "leak" from a block to any
118 other external scope (at least, not without some explicit aliasing
119 action on the part of the block, such as exportation of a symbol
120 from a module). The "point of declaration" is the moment the compiler
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
121 sees "C<my $foo>", not the end of the statement as in Perl 5, so
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
122
123 my $x = $x;
124
125 will no longer see the value of the outer C<$x>; you'll need to say
126 either
127
128 my $x = $OUTER::x;
129
130 or
131
132 my $x = OUTER::<$x>;
133
134 instead.
135
136 If you declare a lexical twice in the same scope, it is the same lexical:
137
138 my $x;
139 my $x;
140
141 By default the second declaration will get a compiler warning.
142 You may suppress this by modifying the first declaration
143 with C<proto>:
144
145 my proto $x;
146 ...
147 while my $x = @x.shift {...} # no warning
148 while my $x = @x.shift {...} # no warning
149
150 If you've referred to C<$x> prior to the first declaration, and the compiler
151 tentatively bound it to C<$OUTER::x>, then it's an error to declare it, and
152 the compiler is required to complain at that point. If such use can't
153 be detected because it is hidden in an eval, then it is erroneous, since
154 the C<eval()> compiler might bind to either C<$OUTER::x> or the subsequently
155 declared "C<my $x>".
156
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
157 As in Perl 5, "C<our $foo>" introduces a lexically scoped alias for
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
158 a variable in the current package.
159
227b34a2 » lwall
2009-11-20 [Specs] more constant cleanups
160 The new C<constant> declarator introduces a
161 compile-time constant, either a variable or named value, which
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
162 may be initialized with a pseudo-assignment:
163
1b1f6dd0 » lwall
2010-01-09 [S04] carry through consistenly on constant being a type declarator s…
164 constant $pi of Int = 3;
165 my Num constant π = atan2(2,2) * 4;
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
166
227b34a2 » lwall
2009-11-20 [Specs] more constant cleanups
167 The initializing expression is evaluated at C<BEGIN> time. Constants
168 (and enums) default to C<our> scoping so they can be accessed from
169 outside the package.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
170
171 There is a new C<state> declarator that introduces a lexically scoped
172 variable like C<my> does, but with a lifetime that persists for the
173 life of the closure, so that it keeps its value from the end of one
174 call to the beginning of the next. Separate clones of the closure
45cff572 » lwall
2010-04-27 [S04] clarify that state is shared by recursion to the same clone
175 get separate state variables. However, recursive calls to the same
176 clone use the same state variable.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
177
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
178 Perl 5's "C<local>" function has been renamed to C<temp> to better
8c3efe4b » moritz
2012-05-27 [S04] small nit
179 reflect what it does. There is also a C<let> prefix operator that sets a
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
180 hypothetical value. It works exactly like C<temp>, except that the
181 value will be restored only if the current block exits unsuccessfully.
182 (See Definition of Success below for more.) C<temp> and C<let> temporize
183 or hypotheticalize the value or the variable depending on whether you
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
184 do assignment or binding. One other difference from Perl 5 is that
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
185 the default is not to undefine a variable. So
186
187 temp $x;
188
189 causes C<$x> to start with its current value. Use
190
191 temp undefine $x;
192
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
193 to get the Perl 5 behavior.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
194
195 Note that temporizations that are undone upon scope exit must be
196 prepared to be redone if a continuation within that scope is taken.
197
198 =head1 The Relationship of Blocks and Statements
199
f80c769c » lwall
2009-11-24 [S04] clarifications suggested by TheDamian++
200 In the absence of explicit control flow terminating the block early,
201 the return value of a block is the value of its final statement.
202 This is defined as the textually last statement of its top-level
203 list of statements; any statements embedded within those top-level
204 statements are in their own lower-level list of statements and,
205 while they may be a final statement in their subscope, they're not
206 considered the final statement of the outer block in question.
207
208 This is subtly different from Perl 5's behavior, which was to return
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
209 the value of the last expression evaluated, even if that expression
f80c769c » lwall
2009-11-24 [S04] clarifications suggested by TheDamian++
210 was just a conditional. Unlike in Perl 5, if a final statement in
211 Perl 6 is a conditional that does not execute any of its branches, it
45ca8c8c » patch
2011-11-20 fix typos
212 doesn't matter what the value of the conditional is, the value of that
f80c769c » lwall
2009-11-24 [S04] clarifications suggested by TheDamian++
213 conditional statement is always C<Nil>. If there are no statements
214 in the block at all, the result is also C<Nil>.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
215
216 =head1 Statement-ending blocks
217
218 A line ending with a closing brace "C<}>", followed by nothing but
219 whitespace or comments, will terminate a statement if an end of statement
220 can occur there. That is, these two statements are equivalent:
221
222 my $x = sub { 3 }
223 my $x = sub { 3 };
224
d1023e2c » lwall
2009-12-15 [S04] remove fossilized restriction dug up by masak++
225 Since bracketed expressions consider their insides to be statements,
226 this works out consistently even where you might expect problems:
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
227
228 my $x = [
229 sub { 3 }, # this comma is not optional
d1023e2c » lwall
2009-12-15 [S04] remove fossilized restriction dug up by masak++
230 sub { 3 } # the statement inside [] terminates here
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
231 ];
232
233 my $hash = {
234 1 => { 2 => 3, 4 => 5 }, # OK
d1023e2c » lwall
2009-12-15 [S04] remove fossilized restriction dug up by masak++
235 2 => { 6 => 7, 8 => 9 } # OK, terminates inner statement
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
236 };
237
238 Because subroutine declarations are expressions, not statements,
239 this is now invalid:
240
241 sub f { 3 } sub g { 3 } # two terms occur in a row
242
243 But these two are valid:
244
245 sub f { 3 }; sub g { 3 };
246 sub f { 3 }; sub g { 3 } # the trailing semicolon is optional
247
248 Though certain control statements could conceivably be parsed in a
249 self-contained way, for visual consistency all statement-terminating
250 blocks that end in the middle of a line I<must> be terminated by
251 semicolon unless they are naturally terminated by some other statement
252 terminator:
253
254 while yin() { yang() } say "done"; # ILLEGAL
255 while yin() { yang() }; say "done"; # okay, explicit semicolon
256 @yy := [ while yin() { yang() } ]; # okay within outer [...]
257 while yin() { yang() } ==> sort # okay, ==> separates statements
258
259 =head1 Conditional statements
2c382016 » szabgab
2009-04-29 adding smartlinks and X<> tags
260 X<if>X<unless>
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
261
262 The C<if> and C<unless> statements work much as they do in
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
263 Perl 5. However, you may omit the parentheses on the conditional:
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
264
265 if $foo == 123 {
266 ...
267 }
268 elsif $foo == 321 {
269 ...
270 }
271 else {
272 ...
273 }
274
1bcf1ffb » lwall
2009-11-11 [S04] clarify Nil semantics of empty blocks and missing branches, pmu…
275 The result of a conditional statement is the result of the block
276 chosen to execute. If the conditional does not execute any
71691eb8 » jdlugosz
2009-05-26 [s04] replace example that no longer was applicable after previous ed…
277 branch, the return value is C<Nil>.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
278
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
279 The C<unless> statement does not allow an C<elsif> or C<else> in Perl 6.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
280
281 The value of the conditional expression may be optionally bound to
282 a closure parameter:
283
284 if testa() -> $a { say $a }
285 elsif testb() -> $b { say $b }
286 else -> $b { say $b }
287
288 Note that the value being evaluated for truth and subsequently bound is
888f27d7 » jdlugosz
2009-05-25 [s04] put in C<...> tags, fix some <...> that have the C missing, typ…
289 not necessarily a value of type C<Bool>. (All normal types in Perl may
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
290 be evaluated for truth. In fact, this construct would be relatively
291 useless if you could bind only boolean values as parameters, since
292 within the closure you already know whether it evaluated to true
293 or false.) Binding within an C<else> automatically binds the value
294 tested by the previous C<if> or C<elsif>, which, while known to be
295 false, might nevertheless be an I<interesting> value of false. (By similar
296 reasoning, an C<unless> allows binding of a false parameter.)
297
298 An explicit placeholder may also be used:
299
300 if blahblah() { return $^it }
301
6828ff44 » sorear
2011-03-05 Fix self-contradiction in S04
302 However, use of C<$_> with a conditional or conditionally repeating
303 statement's block is I<not> considered sufficiently explicit to turn
304 a 0-ary block into a 1-ary function, so all these methods use the
305 same invocant:
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
306
307 if .haste { .waste }
6828ff44 » sorear
2011-03-05 Fix self-contradiction in S04
308 while .haste { .waste }
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
309
310 (Contrast with a non-conditional statement such as:
311
312 for .haste { .waste }
313
314 where each call to the block would bind a new invocant for the
315 C<.waste> method, each of which is likely different from the original
316 invocant to the C<.haste> method.)
317
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
318 Conditional statement modifiers work as in Perl 5. So do the
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
319 implicit conditionals implied by short-circuit operators. Note though that
48e135ab » sorear
2010-05-07 Fix incorrect use of HTML in POD6 in S04
320 the contents of parens or brackets is parsed as a semicolon-separated list of
321 I<statements>,
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
322 so you can say:
323
324 @x = 41, (42 if $answer), 43;
325
326 and that is equivalent to:
327
71691eb8 » jdlugosz
2009-05-26 [s04] replace example that no longer was applicable after previous ed…
328 @x = 41, ($answer ?? 42 !! Nil), 43
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
329
330 =head1 Loop statements
331
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
332 Looping statement modifiers are the same as in Perl 5 except that,
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
333 for ease of writing list comprehensions, a looping statement modifier
334 is allowed to contain a single conditional statement modifier:
335
336 @evens = ($_ * 2 if .odd for 0..100);
337
a826b588 » TimToady
2010-09-06 [S04,S32] implicit loops expect to be controlled by bare next and last
338 Loop modifiers C<next>, C<last>, and C<redo> also work much as in
339 Perl 5. However, the labeled forms can use method call syntax:
340 C<LABEL.next>, etc. The C<.next> and C<.last> methods take an
341 optional argument giving the final value of that loop iteration.
342 So the old C<next LINE> syntax is still allowed but really does
343 something like C<LINE.next(Nil)> underneath. Any block object can
344 be used, not just labels, so to return a value from this iteration
345 of the current block you can say:
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
346
347 &?BLOCK.next($retval);
348
349 [Conjecture: a bare C<next($retval)> function could be taught to do
350 the same, as long as C<$retval> isn't a loop label. Presumably multiple
351 dispatch could sort this out.]
352
a826b588 » TimToady
2010-09-06 [S04,S32] implicit loops expect to be controlled by bare next and last
353 With a target object or label, loop modifiers search lexotically
354 for the scope to modify. Without a target, however, they are purely
355 dynamic, and choose the innermost dynamic loop, which may well be a
356 C<map> or other implicitly looping function, including user-defined
357 functions.
358
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
359 There is no longer a C<continue> block. Instead, use a C<NEXT> block
360 within the body of the loop. See below.
361
362 The value of a loop statement is the list of values from each
3a683f84 » lwall
2010-02-17 [S02,S04] more clarification of when parcels are and aren't used.
363 iteration. Each iteration's value is returned as a single "argument"
364 object. See L<S02> for a long definition of argument, but in short,
365 it's either an ordinary object or a parcel containing multiple values.
366
367 Normal flat list context ignores parcel boundaries and flattens the list.
368 Slice context turns any parcel objects into C<Seq> objects.
369
a826b588 » TimToady
2010-09-06 [S04,S32] implicit loops expect to be controlled by bare next and last
370 Iterations that return C<Nil> (such as by calling C<next> with no extra return
371 arguments) return that C<Nil> as the next value, which will therefore disappear
372 when interpolated in flat context, but will interpolate an empty C<Seq> into slice
3a683f84 » lwall
2010-02-17 [S02,S04] more clarification of when parcels are and aren't used.
373 context.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
374
375 For finer-grained control of which iterations return values, use
376 C<gather> and C<take>.
377
378 Since the final expression in a subroutine returns its value, it's
379 possible to accidentally return a loop's return value when you were
380 only evaluating the loop for its side effects. If you do not wish
381 to accidentally return a list from the final loop statement in a
3bda36af » Util
2011-02-08 Add missing "or"
382 subroutine, place an explicit return statement after it, or use a C<sink>
3a683f84 » lwall
2010-02-17 [S02,S04] more clarification of when parcels are and aren't used.
383 statement prefix on the loop itself.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
384
385 =head2 The C<while> and C<until> statements
0b2523c8 » szabgab
2009-04-29 add some X<> tags
386 X<while>X<until>
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
387
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
388 The C<while> and C<until> statements work as in Perl 5, except that you
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
389 may leave out the parentheses around the conditional:
390
391 while $bar < 100 {
392 ...
393 }
394
395 As with conditionals, you may optionally bind the result of the
396 conditional expression to a parameter of the block:
397
398 while something() -> $thing {
399 ...
400 }
401
34a2c50a » moritz
2009-04-01 [S04] fixed illegal construct, sbp++
402 while something() { ... $^thing ... }
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
403
404 Nothing is ever bound implicitly, however, and many conditionals would
888f27d7 » jdlugosz
2009-05-25 [s04] put in C<...> tags, fix some <...> that have the C missing, typ…
405 simply bind C<True> or C<False> in an uninteresting fashion. This mechanism
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
406 is really only good for objects that know how to return a boolean
407 value and still remain themselves. In general, for most iterated
408 solutions you should consider using a C<for> loop instead (see below).
409 In particular, we now generally use C<for> to iterate filehandles.
410
411 =head2 The C<repeat> statement
0b2523c8 » szabgab
2009-04-29 add some X<> tags
412 X<repeat>X<while>X<next>X<last>X<redo>
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
413
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
414 Unlike in Perl 5, applying a statement modifier to a C<do> block is
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
415 specifically disallowed:
416
417
418 do {
419 ...
420 } while $x < 10; # ILLEGAL
421
422 Instead, you should write the more Pascal-like C<repeat> loop:
423
424 repeat {
425 ...
426 } while $x < 10;
427
428 or equivalently:
429
430 repeat {
431 ...
432 } until $x >= 10;
433
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
434 Unlike Perl 5's C<do-while> loop, this is a real loop block now, so
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
435 C<next>, C<last>, and C<redo> work as expected. The loop conditional
888f27d7 » jdlugosz
2009-05-25 [s04] put in C<...> tags, fix some <...> that have the C missing, typ…
436 on a C<repeat> block is required, so it will be recognized even if you
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
437 put it on a line by its own:
438
439 repeat
440 {
441 ...
442 }
443 while $x < 10;
444
445 However, that's likely to be visually confused with a following
446 C<while> loop at the best of times, so it's also allowed to put the
447 loop conditional at the front, with the same meaning. (The C<repeat>
448 keyword forces the conditional to be evaluated at the end of the loop,
888f27d7 » jdlugosz
2009-05-25 [s04] put in C<...> tags, fix some <...> that have the C missing, typ…
449 so it's still C's C<do-while> semantics.) Therefore, even under GNU style
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
450 rules, the previous example may be rewritten into a very clear:
451
452 repeat while $x < 10
453 {
454 ...
455 }
456
457 or equivalently:
458
459 repeat until $x >= 10
460 {
461 ...
462 }
463
464 As with an ordinary C<while>, you may optionally bind the result of
465 the conditional expression to a parameter of the block:
466
467 repeat -> $thing {
468 ...
469 } while something();
470
471 or
472
473 repeat while something() -> $thing {
474 ...
475 }
476
477 Since the loop executes once before evaluating the condition, the
478 bound parameter will be undefined that first time through the loop.
479
480 =head2 The general loop statement
0b2523c8 » szabgab
2009-04-29 add some X<> tags
481 X<loop>
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
482
483 The C<loop> statement is the C-style C<for> loop in disguise:
484
485 loop ($i = 0; $i < 10; $i++) {
486 ...
487 }
488
489 As in C, the parentheses are required if you supply the 3-part spec; however,
490 the 3-part loop spec may be entirely omitted to write an infinite loop.
491 That is,
492
493 loop {...}
494
495 is equivalent to the Cish idiom:
496
497 loop (;;) {...}
498
499 =head2 The C<for> statement
0b2523c8 » szabgab
2009-04-29 add some X<> tags
500 X<for>X<zip>X<Z>X<STDIN>X<$*IN>X<lines>
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
501
502 There is no C<foreach> statement any more. It's always spelled C<for>
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
503 in Perl 6, so it always takes a list as an argument:
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
504
505 for @foo { .print }
506
507 As mentioned earlier, the loop variable is named by passing a parameter
508 to the closure:
509
510 for @foo -> $item { print $item }
511
512 Multiple parameters may be passed, in which case the list is traversed
513 more than one element at a time:
514
515 for %hash.kv -> $key, $value { print "$key => $value\n" }
516
517 To process two arrays in parallel use the C<zip> function to generate a
518 list that can be bound to the corresponding number of parameters:
519
520 for zip(@a;@b) -> $a, $b { print "[$a, $b]\n" }
521 for @a Z @b -> $a, $b { print "[$a, $b]\n" } # same thing
522
523 The list is evaluated lazily by default, so instead of using a C<while>
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
524 to read a file a line at a time as you would in Perl 5:
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
525
526 while (my $line = <STDIN>) {...}
527
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
528 in Perl 6 you should use a C<for> instead:
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
529
b40f6aea » lwall
2009-04-19 Kill prefix:<=> very, very dead.
530 for $*IN.lines -> $line {...}
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
531
532 This has the added benefit of limiting the scope of the C<$line>
533 parameter to the block it's bound to. (The C<while>'s declaration of
534 C<$line> continues to be visible past the end of the block. Remember,
535 no implicit block scopes.) It is also possible to write
536
b40f6aea » lwall
2009-04-19 Kill prefix:<=> very, very dead.
537 while $*IN.get -> $line {...}
538
539 However, this is likely to fail on autochomped filehandles, so use
540 the C<for> loop instead.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
541
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
542 Note also that Perl 5's special rule causing
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
543
544 while (<>) {...}
545
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
546 to automatically assign to C<$_> is not carried over to Perl 6. That
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
547 should now be written:
548
b40f6aea » lwall
2009-04-19 Kill prefix:<=> very, very dead.
549 for lines() {...}
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
550
551 which is short for
552
b40f6aea » lwall
2009-04-19 Kill prefix:<=> very, very dead.
553 for lines($*ARGFILES) {...}
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
554
555 Arguments bound to the formal parameters of a pointy block are by
556 default readonly within the block. You can declare a parameter
557 read/write by including the "C<is rw>" trait. The following treats
558 every other value in C<@values> as modifiable:
559
560 for @values -> $even is rw, $odd { ... }
561
562 In the case where you want all your parameters to default to C<rw>,
563 you may use the visually suggestive double-ended arrow to indicate that
564 values flow both ways:
565
566 for @values <-> $even, $odd { ... }
567
568 This is equivalent to
569
570 for @values -> $even is rw, $odd is rw { ... }
571
572 If you rely on C<$_> as the implicit parameter to a block,
573 then C<$_> is considered read/write by default. That is,
574 the construct:
575
576 for @foo {...}
577
578 is actually short for:
579
580 for @foo <-> $_ {...}
581
582 so you can modify the current list element in that case.
583
2c525be8 » lwall
2009-06-16 [S04] require temp semantics for topical statement modifiers
584 When used as statement modifiers on implicit blocks (thunks), C<for>
585 and C<given> privately temporize the current value of C<$_> for the
586 left side of the statement and restore the original value at loop exit:
587
588 $_ = 42;
589 .say # 42
590 .say for 1,2,3; # 1,2,3
591 .say; # 42
592
593 The previous value of C<$_> is not available within the loop. If you
594 want it to be available, you must rewrite it as an explicit block
595 using curlies:
596
597 { say OUTER::<$_>, $_ } for 1,2,3; # 421,422,423
598
599 No temporization is necessary with the explicit form since C<$_> is a
600 formal parameter to the block. Likewise, temporization is never needed
601 for C<< statement_control:<for> >> because it always calls a closure.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
602
603 =head2 The do-once loop
604
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
605 In Perl 5, a bare block is deemed to be a do-once loop. In Perl 6,
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
606 the bare block is not a do-once. Instead C<do {...}> is the do-once
607 loop (which is another reason you can't put a statement
608 modifier on it; use C<repeat> for a test-at-the-end loop).
609
9d5a38d5 » Darren_Duncan
2009-07-05 P6 Synopsis : ws changes - remove trailing spaces
610 For any statement, prefixing with a C<do> allows you to
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
611 return the value of that statement and use it in an expression:
612
613 $x = do if $a { $b } else { $c };
614
615 This construct only allows you to attach a single statement to the end
616 of an expression. If you want to continue the expression after the
71691eb8 » jdlugosz
2009-05-26 [s04] replace example that no longer was applicable after previous ed…
617 statement, or if you want to attach multiple statements, you must either
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
618 use the curly form or surround the entire expression in brackets of some sort:
619
577c4fba » pmichaud
2009-06-12 [spec]: Correct buglet in example --
620 @primesquares = (do $_ if prime($_) for 1..100) »**» 2;
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
621
622 Since a bare expression may be used as a statement, you may use C<do>
623 on an expression, but its only effect is to function as an unmatched
624 left parenthesis, much like the C<$> operator in Haskell. That is,
625 precedence decisions do not cross a C<do> boundary, and the missing
626 "right paren" is assumed at the next statement terminator or unmatched
bcf08568 » jdlugosz
2009-05-26 [S04] update code under "do-once loop" in line with current specs.
627 bracket. A C<do> is unnecessary immediately after any opening bracket as
628 the syntax inside brackets is a semicolon-separated list of statements,
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
629 so the above can in fact be written:
630
577c4fba » pmichaud
2009-06-12 [spec]: Correct buglet in example --
631 @primesquares = ($_ if prime($_) for 1..100) »**» 2;
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
632
633 This basically gives us list comprehensions as rvalue expressions:
634
bcf08568 » jdlugosz
2009-05-26 [S04] update code under "do-once loop" in line with current specs.
635 (for 1..100 { $_ if prime($_)}).say
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
636
637 Another consequence of this is that any block just inside a
638 left parenthesis is immediately called like a bare block, so a
639 multidimensional list comprehension may be written using a block with
640 multiple parameters fed by a C<for> modifier:
641
642 @names = (-> $name, $num { "$name.$num" } for 'a'..'zzz' X 1..100);
643
644 or equivalently, using placeholders:
645
646 @names = ({ "$^name.$^num" } for 'a'..'zzz' X 1..100);
647
bcf08568 » jdlugosz
2009-05-26 [S04] update code under "do-once loop" in line with current specs.
648 Since C<do> is defined as going in front of a statement, it follows
649 that it can always be followed by a statement label. This is particularly
023d54be » sunnavy
2009-09-19 typo fix
650 useful for the do-once block, since it is officially a loop and can take
bcf08568 » jdlugosz
2009-05-26 [S04] update code under "do-once loop" in line with current specs.
651 therefore loop control statements.
652
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
653 =head2 Statement-level bare blocks
654
85ef9df4 » carlin
2009-12-12 [S04-control] Fixed a typo
655 Although a bare block occurring as a single statement is no longer
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
656 a do-once loop, it still executes immediately as in Perl 5, as if it
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
657 were immediately dereferenced with a C<.()> postfix, so within such a
7b198c75 » lwall
2009-11-17 [specs] s/CONTEXT/DYNAMIC/ to avoid confusion of concepts
658 block C<CALLER::> refers to the dynamic scope associated
659 with the lexical scope surrounding the block.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
660
661 If you wish to return a closure from a function, you must use an
9d5a38d5 » Darren_Duncan
2009-07-05 P6 Synopsis : ws changes - remove trailing spaces
662 explicit prefix such as C<return> or C<sub> or C<< -> >>.
71691eb8 » jdlugosz
2009-05-26 [s04] replace example that no longer was applicable after previous ed…
663
6e859b2e » Darren_Duncan
2009-07-05 P6 Synopsis : ws changes - all tabs to spaces
664 sub f1
665 {
666 # lots of stuff ...
667 { say "I'm a closure." }
668 }
669
670 my $x1= f1; # fall-off return is result of the say, not the closure.
671
672 sub f2
673 {
674 # lots of stuff ...
675 return { say "I'm a closure." }
676 }
677
678 my $x2= f2; # returns a Block object.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
679
680 Use of a placeholder parameter in statement-level blocks triggers a
681 syntax error, because the parameter is not out front where it can be
682 seen. However, it's not an error when prefixed by a C<do>, or when
683 followed by a statement modifier:
684
685 # Syntax error: Statement-level placeholder block
686 { say $^x };
687
2c525be8 » lwall
2009-06-16 [S04] require temp semantics for topical statement modifiers
688 # Not a syntax error, though $x doesn't get the argument it wants
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
689 do { say $^x };
690
691 # Not an error: Equivalent to "for 1..10 -> $x { say $x }"
692 { say $^x } for 1..10;
693
694 # Not an error: Equivalent to "if foo() -> $x { say $x }"
695 { say $^x } if foo();
696
14dbcacc » lwall
2009-02-27 Document new lift statement for writing generic multis
697 =head2 The C<gather> statement prefix
f1f0a4b1 » moritz
2009-05-03 [S04] a few more X<...> tags
698 X<gather>X<take>
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
699
7ee75f6c » lwall
2010-02-17 [S04] bring gather/take description more in line with modern realities
700 A variant of C<do> is C<gather>. Like C<do>, it is followed by a statement
701 or block, and executes it once. Unlike C<do>, it evaluates the statement or
702 block in sink (void) context; its return value is instead specified by calling
d5e7386c » TimToady
2011-06-23 gather/take user-vs-library considerations
703 the C<take> list prefix operator one or more times within the scope (either lexical or dynamic) of
7ee75f6c » lwall
2010-02-17 [S04] bring gather/take description more in line with modern realities
704 the C<gather>. The C<take> function's signature is like that of C<return>;
705 while having the syntax of a list operator, it merely returns a single item
d5e7386c » TimToady
2011-06-23 gather/take user-vs-library considerations
706 or "argument" (see L<S02> for definition).
707
708 The C<take> function is lexotic if there is a visible outer C<gather>,
709 but falls back to purely dynamic if not. Well, it doesn't really
710 fall back, since a C<take> knows at compile time whether it is being
711 used lexically or dynamically. Less obviously, so does a C<gather>;
712 if a C<gather> lexically contains any C<take> calls, it is marked as
713 lexotic-only, and it will be invisible to a dynamic C<take>. If the
714 C<gather> contains no C<take> lexically, it by definition cannot be
715 the lexotic target of any C<take>, so it can only harvest dynamic
716 C<take> calls. The only remaining difficulty arises if both the user
717 and a library writer attempt to use dynamic gather with user-defined
718 callbacks that contain C<take>. So we will say that it is erroneous
719 for a library writer to mix dynamic gather with callbacks unless
720 those callbacks are somehow "ungathered" to the outer dynamic scope.
721 [Conjecture: there should either be an C<callergather> primitive that
722 does this, or it should be added to the job description of C<lift>.
723 A third option is to allow labeled C<gather>/C<take> for such a situation,
724 and dynamic C<take> must match the C<gather>'s label (or lack thereof) exactly.
725 (Using the term "label" loosely, to include other solutions besides the label syntax,
726 such as .gather and .take methods on some identity object.)]
3a683f84 » lwall
2010-02-17 [S02,S04] more clarification of when parcels are and aren't used.
727
728 If you take multiple items in a comma list (since it is, after all, a list
729 operator), they will be wrapped up in a C<Parcel> object for return as the
730 next argument. No additional context is applied by the C<take> operator,
731 since all context is lazy in Perl 6. The flattening or slicing of any such
732 returned parcel will be dependent on how the C<gather>'s return iterator is
733 iterated (with C<.get> vs C<.getarg>).
734
735 The value returned by the C<take> to the C<take>'s own context is that same
736 returned argument (which is ignored when the C<take> is in sink context).
737 Regardless of the C<take>'s immediate context, the object returned is also
738 added to the list of values being gathered, which is returned by the C<gather>
739 as a lazy list (that is, an iterator, really), with each argument element
740 of that list corresponding to one C<take>.
741
742 Any parcels in the returned list are normally flattened when bound
b962f00f » TimToady
2010-09-16 refine tree contexts; slice context -> lol context
743 into flat context. When bound into a lol context, however,
744 the parcel objects become real C<List> objects that keep their
7ee75f6c » lwall
2010-02-17 [S04] bring gather/take description more in line with modern realities
745 identity as discrete sublists. The eventual binding context thus
746 determines whether to throw away or keep the groupings resulting from
3a683f84 » lwall
2010-02-17 [S02,S04] more clarification of when parcels are and aren't used.
747 each individual C<take> call. Most list contexts are flat
748 rather than sliced, so the boundaries between individual C<take>
749 calls usually disappear. (FLAT is an acronym meaning Flat Lists Are Typical. :)
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
750
b193100e » lwall
2009-11-20 [S02,3,4] attempt to rename void context to sink context and see if i…
751 Because C<gather> evaluates its block or statement in sink context,
752 this typically causes the C<take> function to be evaluated in sink
753 context. However, a C<take> function that is not in sink context
7ee75f6c » lwall
2010-02-17 [S04] bring gather/take description more in line with modern realities
754 gathers its return objects I<en passant> and also returns them unchanged.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
755 This makes it easy to keep track of what you last "took":
756
757 my @uniq = gather for @list {
758 state $previous = take $_;
759 next if $_ === $previous;
760 $previous = take $_;
761 }
762
763 The C<take> function essentially has two contexts simultaneously, the
888f27d7 » jdlugosz
2009-05-25 [s04] put in C<...> tags, fix some <...> that have the C missing, typ…
764 context in which the C<gather> is operating, and the context in which the
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
765 C<take> is operating. These need not be identical contexts, since they
c11d0ee6 » lwall
2010-02-01 [S02,S03,S04] more @@ removal; some s/Capture/Parcel/ cleanup
766 may bind or coerce the resulting parcels differently:
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
767
768 my @y;
c11d0ee6 » lwall
2010-02-01 [S02,S03,S04] more @@ removal; some s/Capture/Parcel/ cleanup
769 @x = gather for 1..2 { # flat context for list of parcels
7ee75f6c » lwall
2010-02-17 [S04] bring gather/take description more in line with modern realities
770 my ($y) := take $_, $_ * 10; # item context promotes parcel to seq
771 push @y, $y;
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
772 }
7ee75f6c » lwall
2010-02-17 [S04] bring gather/take description more in line with modern realities
773 # @x contains 4 Ints: 1,10,2,20 flattened by list assignment to @x
774 # @y contains 2 Seqs: Seq(1,10),Seq(2,20) sliced by binding to positional $y
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
775
7ee75f6c » lwall
2010-02-17 [S04] bring gather/take description more in line with modern realities
776 Likewise, we can just remember the gather's result parcel by binding and
777 later coercing it:
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
778
7ee75f6c » lwall
2010-02-17 [S04] bring gather/take description more in line with modern realities
779 my |$c := gather for 1..2 {
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
780 take $_, $_ * 10;
781 }
c11d0ee6 » lwall
2010-02-01 [S02,S03,S04] more @@ removal; some s/Capture/Parcel/ cleanup
782 # $c.flat produces 1,10,2,20 -- flatten fully into a list of Ints.
621ba5e0 » lichtkind
2012-04-24 s/.slice/.lol/
783 # $c.lol produces Seq(1,10),Seq(2,20) -- list of Seqs, a 2-D list.
7ee75f6c » lwall
2010-02-17 [S04] bring gather/take description more in line with modern realities
784 # $c.item produces Seq((1,10),(2,20)) -- coerced to Seq of unresolved Parcels
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
785
b193100e » lwall
2009-11-20 [S02,3,4] attempt to rename void context to sink context and see if i…
786 Note that the C<take> itself is in sink context in this example because
7ee75f6c » lwall
2010-02-17 [S04] bring gather/take description more in line with modern realities
787 the C<for> loop is in the sink context provided inside the gather.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
788
789 A C<gather> is not considered a loop, but it is easy to combine with a loop
790 statement as in the examples above.
791
15be004b » lwall
2010-02-18 [S04] unmuddying requested by Richard Hainsworth++
792 The C<take> operation may be defined internally using resumable control
793 exceptions, or dynamic variables, or pigeons carrying clay tablets.
794 The choice any particular implementation makes is specifically I<not> part
795 of the definition of Perl 6, and you should not rely on it in portable code.
796
14dbcacc » lwall
2009-02-27 Document new lift statement for writing generic multis
797 =head2 The C<lift> statement prefix
f1f0a4b1 » moritz
2009-05-03 [S04] a few more X<...> tags
798 X<lift>
14dbcacc » lwall
2009-02-27 Document new lift statement for writing generic multis
799
800 When writing generic multi routines you often want to write a bit of
dff23644 » lwall
2009-11-20 [Spec] slaughter various confusing overloadings of the term 'context'
801 code whose meaning is dependent on the linguistic context of the caller. It's
14dbcacc » lwall
2009-02-27 Document new lift statement for writing generic multis
802 somewhat like virtual methods where the actual call depends on the type
803 of the invocant, but here the "invocant" is really the lexical scope of
804 the caller, and the virtual calls are name bindings. Within a lift,
805 special rules apply to how names are looked up. Only names defined
806 in the lexical scope of the immediately surrounding routine are considered concrete.
807 All other names (including implicit names of operators) are looked up
808 in the lexical scope of the caller when we actually know who the caller
809 is at run time. (Note the caller can vary from call to call!)
71691eb8 » jdlugosz
2009-05-26 [s04] replace example that no longer was applicable after previous ed…
810
811 This applies to anything that needs to be looked up at compile time, including
812 names of variables, and named values such as types and subs.
813
14dbcacc » lwall
2009-02-27 Document new lift statement for writing generic multis
814 Through this mechanism, a generic multi can redirect execution to
815 a more specific version, but the candidate list for this redirection
816 is determined by the caller, not by the lexical scope of the multi,
817 which can't see the caller's lexical scope except through the CALLER::
818 pseudo package. For example, Perl forces generic C<eq> to coerce to
819 string comparison, like this:
820
6e859b2e » Darren_Duncan
2009-07-05 P6 Synopsis : ws changes - all tabs to spaces
821 proto infix:<eq> (Any $a, Any $b) { lift ~$a eq ~$b } # user's eq, user's ~
822 multi infix:<eq> (Whatever, Any $b) { -> $a { lift $a eq $b } } # user's eq
823 multi infix:<eq> (Any $a, Whatever) { -> $b { lift $a eq $b } } # user's eq
824 multi infix:<eq> (&f:($), Any $b) { -> $a { lift f($a) eq $b } } # user's eq
825 multi infix:<eq> (Str $a, Str $b) { !Str::leg($a, $b) } # primitive leg, primitive !
14dbcacc » lwall
2009-02-27 Document new lift statement for writing generic multis
826
827
35e45d44 » lwall
2009-02-27 typo from Jon++
828 Note that in each piece of lifted code there are references to
14dbcacc » lwall
2009-02-27 Document new lift statement for writing generic multis
829 variables defined in the multi, such as C<$a>, C<$b>, and C<&f>.
830 These are taken at face value. Everything else within a lift is
dff23644 » lwall
2009-11-20 [Spec] slaughter various confusing overloadings of the term 'context'
831 assumed to mean something in the caller's linguistic context. (This implies
14dbcacc » lwall
2009-02-27 Document new lift statement for writing generic multis
832 that there are some errors that would ordinarily be found at
833 compile time that cannot be found until we know what the caller's
834 lexical scope looks like at run time. That's okay.)
835
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
836 =head2 Other C<do>-like forms
f1f0a4b1 » moritz
2009-05-03 [S04] a few more X<...> tags
837 X<do>
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
838
888f27d7 » jdlugosz
2009-05-25 [s04] put in C<...> tags, fix some <...> that have the C missing, typ…
839 Other similar forms, where a keyword is followed by code to be controlled by it, may also take bare statements,
b193100e » lwall
2009-11-20 [S02,3,4] attempt to rename void context to sink context and see if i…
840 including C<try>, C<quietly>, C<contend>, C<async>, C<lazy>, and C<sink>. These constructs
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
841 establish a dynamic scope without necessarily establishing a lexical
842 scope. (You can always establish a lexical scope explicitly by using
843 the block form of argument.) As statement introducers, all these
844 keywords must be followed by whitespace. (You can say something
845 like C<try({...})>, but then you are calling the C<try()> function
846 using function call syntax instead, and since Perl does not supply
847 such a function, it will be assumed to be a user-defined function.)
848 For purposes of flow control, none of these forms are considered loops,
849 but they may easily be applied to a normal loop.
850
14268d1b » lwall
2009-05-04 [S04] clarify parsing of statement controls
851 Note that any construct in the statement_prefix category defines
852 special syntax. If followed by a block it does not parse as a
853 list operator or even as a prefix unary; it will never look for any
854 additional expression following the block. In particular,
855
856 foo( try {...}, 2, 3 )
857
858 calls the C<foo> function with three arguments. And
859
860 do {...} + 1
861
862 add 1 to the result of the do block. On the other hand, if a
c17f41e6 » lwall
2009-05-04 [S04] previous patch confused statement prefixes with statement controls
863 statement_prefix is followed by a non-block statement, all nested
864 blockless statement_prefixes will terminate at the same statement
14268d1b » lwall
2009-05-04 [S04] clarify parsing of statement controls
865 ending:
866
867 do do do foo(); bar 43;
868
869 is parsed as:
870
871 do { do { do { foo(); }}}; bar(43);
872
873
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
874 =head1 Switch statements
0b2523c8 » szabgab
2009-04-29 add some X<> tags
875 X<given>X<when>X<switch>X<case>X<default>
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
876
877 A switch statement is a means of topicalizing, so the switch keyword
878 is the English topicalizer, C<given>. The keyword for individual
879 cases is C<when>:
880
881 given EXPR {
882 when EXPR { ... }
883 when EXPR { ... }
884 default { ... }
885 }
886
887 The current topic is always aliased to the special variable C<$_>.
888 The C<given> block is just one way to set the current topic, but
889 a switch statement can be any block that sets C<$_>, including a
890 C<for> loop (assuming one of its loop variables is bound to C<$_>)
891 or the body of a method (if you have declared the invocant as C<$_>).
892 So switching behavior is actually caused by the C<when> statements in
893 the block, not by the nature of the block itself. A C<when> statement
894 implicitly does a "smart match" between the current topic (C<$_>) and
895 the argument of the C<when>. If the smart match succeeds, C<when>'s
896 associated block is executed, and the innermost surrounding block
897 that has C<$_> as one of its formal parameters (either explicit
898 or implicit) is automatically broken out of. (If that is not the
899 block you wish to leave, you must use the C<LABEL.leave> method (or some
900 other control exception such as C<return> or C<next>) to
901 be more specific, since the compiler may find it difficult to guess
902 which surrounding construct was intended as the actual topicalizer.)
903 The value of the inner block is returned as the value of the outer
904 block.
905
f8bc519c » lwall
2009-12-18 [S04] rename break/nobreak to succeed/proceed
906 If the smart match fails, control proceeds the next statement
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
907 normally, which may or may not be a C<when> statement. Since C<when>
908 statements are presumed to be executed in order like normal statements,
909 it's not required that all the statements in a switch block be C<when>
910 statements (though it helps the optimizer to have a sequence of
911 contiguous C<when> statements, because then it can arrange to jump
912 directly to the first appropriate test that might possibly match.)
913
914 The default case:
915
916 default {...}
917
918 is exactly equivalent to
919
920 when * {...}
921
922 Because C<when> statements are executed in order, the default must
923 come last. You don't have to use an explicit default--you can just
924 fall off the last C<when> into ordinary code. But use of a C<default>
925 block is good documentation.
926
927 If you use a C<for> loop with a parameter named C<$_> (either
928 explicitly or implicitly), that parameter can function as the topic
929 of any C<when> statements within the loop.
930
931 You can explicitly break out of a C<when> block (and its surrounding
f8bc519c » lwall
2009-12-18 [S04] rename break/nobreak to succeed/proceed
932 topicalizer block) early using the C<succeed> verb. More precisely,
eba1f441 » lwall
2009-09-05 [S04] clarify semantics of break for masak++
933 it first scans outward (lexically) for the innermost containing
934 C<when> block. From there it continues to scan outward to find the
4b75bad6 » TimToady
2011-08-10 Minor clarifications to 'succeed' semantics
935 innermost block outside the C<when> that defines C<$_>,
936 either explicitly or implicitly. (Note that
eba1f441 » lwall
2009-09-05 [S04] clarify semantics of break for masak++
937 both of these scans are done at compile time; if the scans fail,
938 it's a compile-time semantic error.) Typically, such an outer
f8bc519c » lwall
2009-12-18 [S04] rename break/nobreak to succeed/proceed
939 block will be the block of a C<given> or a C<for> statement, but any block that
4b75bad6 » TimToady
2011-08-10 Minor clarifications to 'succeed' semantics
940 sets the topic can be broken out of. At run time,
f8bc519c » lwall
2009-12-18 [S04] rename break/nobreak to succeed/proceed
941 C<succeed> uses a control exception to scan up the dynamic chain to
dff23644 » lwall
2009-11-20 [Spec] slaughter various confusing overloadings of the term 'context'
942 find the call frame belonging to that same outer block, and
943 when it has found that frame, it does a C<.leave> on it to unwind
f8bc519c » lwall
2009-12-18 [S04] rename break/nobreak to succeed/proceed
944 the call frames. If any arguments are supplied to the C<succeed> function,
eba1f441 » lwall
2009-09-05 [S04] clarify semantics of break for masak++
945 they are passed out via the C<leave> method. Since leaving a block is
f8bc519c » lwall
2009-12-18 [S04] rename break/nobreak to succeed/proceed
946 considered a successful return, breaking out of one with C<succeed> is also considered
947 a successful return for the purposes of C<KEEP> and C<UNDO>.
948
949 The implicit break of a normal
381b8d30 » lwall
2009-12-16 [S04] slight clarification to break semantics
950 C<when> block works the same way, returning the value of the entire
f8bc519c » lwall
2009-12-18 [S04] rename break/nobreak to succeed/proceed
951 block (normally from its last statement) via an implicit C<succeed>.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
952
953 You can explicitly leave a C<when> block and go to the next statement
f8bc519c » lwall
2009-12-18 [S04] rename break/nobreak to succeed/proceed
954 following the C<when> by using C<proceed>. (Note that, unlike C's
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
955 idea of "falling through", subsequent C<when> conditions are evaluated.
956 To jump into the next C<when> block without testing its condition,
eba1f441 » lwall
2009-09-05 [S04] clarify semantics of break for masak++
957 you must use a C<goto>. But generally that means you should refactor
958 instead.)
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
959
4b75bad6 » TimToady
2011-08-10 Minor clarifications to 'succeed' semantics
960 If you have a switch that is the main block of a C<for> loop that uses C<$_> as its loop variable, and
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
961 you break out of the switch either implicitly or explicitly (that is,
962 the switch "succeeds"), control merely goes to the end of that block,
963 and thence on to the next iteration of the loop. You must use C<last>
964 (or some more violent control exception such as C<return>) to break
965 out of the entire loop early. Of course, an explicit C<next> might
a826b588 » TimToady
2010-09-06 [S04,S32] implicit loops expect to be controlled by bare next and last
966 be clearer than a C<succeed> if you really want to go directly to the
f8bc519c » lwall
2009-12-18 [S04] rename break/nobreak to succeed/proceed
967 next iteration. On the other hand, C<succeed> can take an optional
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
968 argument giving the value for that iteration of the loop. As with
f8bc519c » lwall
2009-12-18 [S04] rename break/nobreak to succeed/proceed
969 the C<.leave> method, there is also a C<.succeed> method to break from a
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
970 labelled block functioning as a switch:
971
f8bc519c » lwall
2009-12-18 [S04] rename break/nobreak to succeed/proceed
972 OUTER.succeed($retval)
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
973
ce5171c8 » lwall
2009-04-17 Document the 'when' statement modifier.
974 There is a C<when> statement modifier, but it does not have any
f8bc519c » lwall
2009-12-18 [S04] rename break/nobreak to succeed/proceed
975 breakout semantics; it is merely a smartmatch against
976 the current topic. That is,
ce5171c8 » lwall
2009-04-17 Document the 'when' statement modifier.
977
978 doit() when 42;
979
980 is exactly equivalent to
981
982 doit() if $_ ~~ 42;
983
f80c769c » lwall
2009-11-24 [S04] clarifications suggested by TheDamian++
984 This is particularly useful for list comprehensions:
985
986 @lucky = ($_ when /7/ for 1..100);
987
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
988 =head1 Exception handlers
0b2523c8 » szabgab
2009-04-29 add some X<> tags
989 X<CATCH>
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
990
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
991 Unlike many other languages, Perl 6 specifies exception handlers by
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
992 placing a C<CATCH> block I<within> that block that is having its exceptions
993 handled.
994
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
995 The Perl 6 equivalent to Perl 5's C<eval {...}> is C<try {...}>.
536a4833 » moritz
2012-04-09 [S04] note one more that &eval does not catch exceptions
996 (Perl 6's C<eval> function only evaluates strings, not blocks, and
997 does not catch exceptions.)
63471cb2 » lwall
2009-10-01 [S04] add statement_prefix:<quietly>
998 A C<try> block by default has a C<CATCH> block that handles all fatal
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
999 exceptions by ignoring them. If you define a C<CATCH> block within
1000 the C<try>, it replaces the default C<CATCH>. It also makes the C<try>
1001 keyword redundant, because any block can function as a C<try> block
1002 if you put a C<CATCH> block within it.
1003
1004 An exception handler is just a switch statement on an implicit topic
aca4e5d2 » TimToady
2011-07-08 detangling $! from inflight semantics of @!
1005 that happens to be the current exception to be dealt with.
1006 Inside the C<CATCH> block, the exception in question is
1007 bound to C<$_>. Because of smart matching,
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1008 ordinary C<when> statements are sufficiently powerful to pattern
1009 match the current exception against classes or patterns or numbers
1010 without any special syntax for exception handlers. If none of the
aca4e5d2 » TimToady
2011-07-08 detangling $! from inflight semantics of @!
1011 cases in the C<CATCH> handles the exception, the exception will be rethrown.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1012 To ignore all unhandled exceptions, use an empty C<default> case.
aca4e5d2 » TimToady
2011-07-08 detangling $! from inflight semantics of @!
1013 (In other words, there is an implicit C<.die> just inside the end
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1014 of the C<CATCH> block. Handled exceptions break out past this implicit
6bbdcc67 » Kodi
2009-09-24 [S04] Made CATCH's special treatment of default blocks, which is alre…
1015 rethrow.) Hence, C<CATCH> is unlike all other switch statements in that
1016 it treats code inside a C<default> block differently from code that's after
1017 all the C<when> blocks but not in a C<default> block.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1018
e1d43ee4 » lwall
2010-07-12 [S04] try to nail down CATCH exit semantics a bit more water-tightly
1019 More specifically, when you write:
1020
1021 CATCH {
1022 when Mumble {...}
1023 default {...}
1024 }
1025
aca4e5d2 » TimToady
2011-07-08 detangling $! from inflight semantics of @!
1026 you're really calling into a I<catch lambda> that works
1027 something like this:
e1d43ee4 » lwall
2010-07-12 [S04] try to nail down CATCH exit semantics a bit more water-tightly
1028
aca4e5d2 » TimToady
2011-07-08 detangling $! from inflight semantics of @!
1029 -> *@! {
15c37f83 » TimToady
2011-08-05 refine relationship of CATCH to outer caller's $!
1030 my @handled = ();
1031 my @unhandled = ();
aca4e5d2 » TimToady
2011-07-08 detangling $! from inflight semantics of @!
1032 my @*undead = ();
e1d43ee4 » lwall
2010-07-12 [S04] try to nail down CATCH exit semantics a bit more water-tightly
1033
aca4e5d2 » TimToady
2011-07-08 detangling $! from inflight semantics of @!
1034 for @! {
0e7e19cc » TimToady
2011-08-30 refinement of SIMPLECATCH semantics
1035 # note, fails current iteration, continues with loop
1036 SIMPLECATCH { push @*undead, $_; push @unhandled, OUTER::<$_>; }
15c37f83 » TimToady
2011-08-05 refine relationship of CATCH to outer caller's $!
1037
0e7e19cc » TimToady
2011-08-30 refinement of SIMPLECATCH semantics
1038 .handled = True;
52e578e9 » lwall
2010-07-14 [S04] revise catcher semantics semantics to allow $!.handled = 1 to w…
1039 when Mumble {...}
1040 default {...}
0e7e19cc » TimToady
2011-08-30 refinement of SIMPLECATCH semantics
1041 .handled = False;
15c37f83 » TimToady
2011-08-05 refine relationship of CATCH to outer caller's $!
1042
a0d5a9ed » jnthn
2012-03-08 A couple of fixes to the exceptions spec.
1043 push @unhandled, $_;
0e7e19cc » TimToady
2011-08-30 refinement of SIMPLECATCH semantics
1044
1045 KEEP { push @handled, $_ if .handled }
52e578e9 » lwall
2010-07-14 [S04] revise catcher semantics semantics to allow $!.handled = 1 to w…
1046 }
e1d43ee4 » lwall
2010-07-12 [S04] try to nail down CATCH exit semantics a bit more water-tightly
1047
15c37f83 » TimToady
2011-08-05 refine relationship of CATCH to outer caller's $!
1048 push @unhandled, @*undead;
a7170aa6 » TimToady
2011-08-05 no need to set $! if we're rethrowing past it
1049
1050 # no point in setting their $! if we're gonna blow past
1051 set_outer_caller's_bang(@handled) unless @unhandled;
1052
15c37f83 » TimToady
2011-08-05 refine relationship of CATCH to outer caller's $!
1053 @unhandled;
e1d43ee4 » lwall
2010-07-12 [S04] try to nail down CATCH exit semantics a bit more water-tightly
1054 }
1055
aca4e5d2 » TimToady
2011-07-08 detangling $! from inflight semantics of @!
1056 Whenever an exception occurs during the execution of a handler,
1057 it is pushed onto the end of the C<@*undead> array for later processing
1058 by an outer handler. If there are any unhandled C<@!> exceptions,
1059 or if any exceptions were caught by the inner SIMPLECATCH (which does
a0d5a9ed » jnthn
2012-03-08 A couple of fixes to the exceptions spec.
1060 nothing but runs its push code, which should not produce any exceptions),
1061 then the CATCH block returns them to the exception thrower.
aca4e5d2 » TimToady
2011-07-08 detangling $! from inflight semantics of @!
1062
52e578e9 » lwall
2010-07-14 [S04] revise catcher semantics semantics to allow $!.handled = 1 to w…
1063 The exception thrower looks up the call stack for a catch lambda
aca4e5d2 » TimToady
2011-07-08 detangling $! from inflight semantics of @!
1064 that returns () to indicate all exceptions are handled, and then it is happy,
1065 and unwinds the stack to that point. If any exceptions are returned
a0d5a9ed » jnthn
2012-03-08 A couple of fixes to the exceptions spec.
1066 as not handled, the exception thrower keeps looking for a higher
52e578e9 » lwall
2010-07-14 [S04] revise catcher semantics semantics to allow $!.handled = 1 to w…
1067 dynamic scope for a spot to unwind to. Note that any C<die> in the
aca4e5d2 » TimToady
2011-07-08 detangling $! from inflight semantics of @!
1068 catch lambda eventually rethrows outside the lambda as a new exception, but
1069 not until the current exception handler has a chance to handle all
1070 exceptions that came in via C<@!>.
1071
1072 Resumable exceptions may or may not leave
52e578e9 » lwall
2010-07-14 [S04] revise catcher semantics semantics to allow $!.handled = 1 to w…
1073 normally depending on the implementation. If continuations are used,
aca4e5d2 » TimToady
2011-07-08 detangling $! from inflight semantics of @!
1074 the C<.resume> call will simply goto the continuation in question,
52e578e9 » lwall
2010-07-14 [S04] revise catcher semantics semantics to allow $!.handled = 1 to w…
1075 and the lambda's callframe is abandoned. Resumable exceptions may also
aca4e5d2 » TimToady
2011-07-08 detangling $! from inflight semantics of @!
1076 be implemented by simply marking the current exception as "resumed",
52e578e9 » lwall
2010-07-14 [S04] revise catcher semantics semantics to allow $!.handled = 1 to w…
1077 in which case the original exception thrower simply returns to
1078 the code that threw the resumable exception, rather than unwinding
aca4e5d2 » TimToady
2011-07-08 detangling $! from inflight semantics of @!
1079 before returning. This could be done by pushing the resumed exception
1080 onto the unhandled list, and then the thrower checking to see if there is only
1081 a single resumed exception in the "unhandled" list. The unhandled list
1082 is a dynamic variable so that it's easy for .resume to manipulate it.
52e578e9 » lwall
2010-07-14 [S04] revise catcher semantics semantics to allow $!.handled = 1 to w…
1083
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1084 A C<CATCH> block sees the lexical scope in which it was defined, but
1085 its caller is the dynamic location that threw the exception. That is,
1086 the stack is not unwound until some exception handler chooses to
1087 unwind it by "handling" the exception in question. So logically,
1088 if the C<CATCH> block throws its own exception, you would expect the
1089 C<CATCH> block to catch its own exception recursively forever. However,
1090 a C<CATCH> must not behave that way, so we say that a C<CATCH> block
1091 never attempts to handle any exception thrown within its own dynamic scope.
aca4e5d2 » TimToady
2011-07-08 detangling $! from inflight semantics of @!
1092 (Otherwise any C<die> would cause an infinite loop.) Instead we treasure
1093 them up and rethrow them to a handler further up.
bfd9ece5 » lwall
2010-07-14 [S04] more bombastic utterances about not dropping pending exceptions
1094
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1095 =head1 Control Exceptions
1096
1097 All abnormal control flow is, in the general case, handled by the
1098 exception mechanism (which is likely to be optimized away in specific
1099 cases.) Here "abnormal" means any transfer of control outward that
1100 is not just falling off the end of a block. A C<return>,
1101 for example, is considered a form of abnormal control flow, since it
1102 can jump out of multiple levels of closures to the end of the scope
1103 of the current subroutine definition. Loop commands like C<next>
1104 are abnormal, but looping because you hit the end of the block is not.
a826b588 » TimToady
2010-09-06 [S04,S32] implicit loops expect to be controlled by bare next and last
1105 The implicit break (what C<succeed> does explicitly) of a C<when> block is abnormal.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1106
1107 A C<CATCH> block handles only "bad" exceptions, and lets control
1108 exceptions pass unhindered. Control exceptions may be caught with a
1109 C<CONTROL> block. Generally you don't need to worry about this unless
1110 you're defining a control construct. You may have one C<CATCH> block
1111 and one C<CONTROL> block, since some user-defined constructs may wish to
1112 supply an implicit C<CONTROL> block to your closure, but let you define
1113 your own C<CATCH> block.
1114
1115 A C<return> always exits from the lexically surrounding sub
1116 or method definition (that is, from a function officially declared
1117 with the C<sub>, C<method>, or C<submethod> keywords). Pointy blocks
71691eb8 » jdlugosz
2009-05-26 [s04] replace example that no longer was applicable after previous ed…
1118 and bare closures are transparent to C<return>, in that the C<return>
1119 statement still means C<&?ROUTINE.leave> from the C<Routine> that existed
1120 in dynamic scope when the closure was cloned.
1121
dff23644 » lwall
2009-11-20 [Spec] slaughter various confusing overloadings of the term 'context'
1122 It is illegal to return from the closure if that C<Routine> no longer owns
1123 a call frame in the current call stack.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1124
71691eb8 » jdlugosz
2009-05-26 [s04] replace example that no longer was applicable after previous ed…
1125 To return a value (to the dynamical caller) from any pointy block or bare closure, you either
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1126 just let the block return the value of its final expression, or you
1127 can use C<leave>, which comes in both function and method forms.
1128 The function (or listop) form always exits from the innermost block,
1129 returning its arguments as the final value of the block exactly as
888f27d7 » jdlugosz
2009-05-25 [s04] put in C<...> tags, fix some <...> that have the C missing, typ…
1130 C<return> does. The method form will leave any block in the dynamic
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1131 scope that can be named as an object and that responds to the C<.leave>
1132 method.
1133
1134 Hence, the C<leave> function:
1135
1136 leave(1,2,3)
1137
1138 is really just short for:
1139
1140 &?BLOCK.leave(1,2,3)
1141
1142 To return from your immediate caller, you can say:
1143
1144 caller.leave(1,2,3)
1145
dff23644 » lwall
2009-11-20 [Spec] slaughter various confusing overloadings of the term 'context'
1146 Further call frames up the caller stack may be located by use of the
1147 C<callframe> function:
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1148
dff23644 » lwall
2009-11-20 [Spec] slaughter various confusing overloadings of the term 'context'
1149 callframe({ .labels.any eq 'LINE' }).leave(1,2,3);
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1150
dff23644 » lwall
2009-11-20 [Spec] slaughter various confusing overloadings of the term 'context'
1151 By default the innermost call frame matching the selection criteria
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1152 will be exited. This can be a bit cumbersome, so in the particular
1153 case of labels, the label that is already visible in the current lexical
1154 scope is considered a kind of pseudo object specifying a potential
1155 dynamic context. If instead of the above you say:
1156
1157 LINE.leave(1,2,3)
1158
1159 it was always exit from your lexically scoped C<LINE> loop, even
1160 if some inner dynamic scope you can't see happens to also have that
dff23644 » lwall
2009-11-20 [Spec] slaughter various confusing overloadings of the term 'context'
1161 label. (In other words, it's lexotic.) If the C<LINE> label is visible but you aren't actually in
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1162 a dynamic scope controlled by that label, an exception is thrown.
1163 (If the C<LINE> is not visible, it would have been caught earlier at
1164 compile time since C<LINE> would likely be a bareword.)
1165
1166 In theory, any user-defined control construct can catch any control
1167 exception it likes. However, there have to be some culturally enforced
1168 standards on which constructs capture which exceptions. Much like
1169 C<return> may only return from an "official" subroutine or method,
1170 a loop exit like C<next> should be caught by the construct the user
a826b588 » TimToady
2010-09-06 [S04,S32] implicit loops expect to be controlled by bare next and last
1171 expects it to be caught by. (Always assuming the user expects the
1172 right thing, of course...) In particular, if the user labels a loop
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1173 with a specific label, and calls a loop control from within the lexical
1174 scope of that loop, and if that call mentions the outer loop's label,
1175 then that outer loop is the one that must be controlled. In other words,
1176 it first tries this form:
1177
1178 LINE.leave(1,2,3)
1179
1180 If there is no such lexically scoped outer loop in the current subroutine,
1181 then a fallback search is made outward through the dynamic scopes in
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
1182 the same way Perl 5 does. (The difference between Perl 5 and Perl 6
1183 in this respect arises only because Perl 5 didn't have user-defined
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1184 control structures, hence the sub's lexical scope was I<always>
1185 the innermost dynamic scope, so the preference to the lexical scope
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
1186 in the current sub was implicit. For Perl 6 we have to make this
dff23644 » lwall
2009-11-20 [Spec] slaughter various confusing overloadings of the term 'context'
1187 preference for lexotic behavior explicit.)
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1188
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
1189 Warnings are produced in Perl 6 by throwing a resumable control
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1190 exception to the outermost scope, which by default prints the
1191 warning and resumes the exception by extracting a resume continuation
888f27d7 » jdlugosz
2009-05-25 [s04] put in C<...> tags, fix some <...> that have the C missing, typ…
1192 from the exception, which must be supplied by the C<warn()> function
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
1193 (or equivalent). Exceptions are not resumable in Perl 6 unless
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1194 the exception object does the C<Resumable> role. (Note that fatal
1195 exception types can do the C<Resumable> role even if thrown via
1196 C<fail()>--when uncaught they just hit the outermost fatal handler
1197 instead of the outermost warning handler, so some inner scope has to
1198 explicitly treat them as warnings and resume them.)
1199
1200 Since warnings are processed using the standard control exception
1201 mechanism, they may be intercepted and either suppressed or fatalized
1202 anywhere within the dynamic scope by supplying a suitable C<CONTROL>
1203 block. This dynamic control is orthogonal to any lexically scoped
1204 warning controls, which merely decide whether to call C<warn()>
1205 in the first place.
1206
1207 As with calls to C<return>, the warning control exception is an
1208 abstraction that the compiler is free to optimize away (along with the
1209 associated continuation) when the compiler or runtime can determine
1210 that the semantics would be preserved by merely printing out the
1211 error and going on. Since all exception handlers run in the dynamic
dff23644 » lwall
2009-11-20 [Spec] slaughter various confusing overloadings of the term 'context'
1212 scope of the throw, that reduces to simply returning from the C<warn>
52e578e9 » lwall
2010-07-14 [S04] revise catcher semantics semantics to allow $!.handled = 1 to w…
1213 function most of the time. See previous section for discussion of
1214 ways to return from catch lambdas. The control lambda is logically
1215 separate from the catch lambda, though an implementation is allowed
1216 to combine them if it is careful to retain separate semantics for
1217 catch and control exceptions.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1218
003891a8 » TimToady
2012-07-28 Explication of lazy warnings
1219 One additional level of control is the notion of I<lazy warnings>.
1220 If, instead of throwing a warning directly, the program calls C<fail()>
1221 with a resumable exception, the throwing of the warning is delayed
1222 until first use (or the caller's policy) requires it to be thrown.
1223 If the warning exception supports the C<.resume_value> method, that
1224 will be the value of the failure after it has resumed. Otherwise the
838a4b98 » TimToady
2012-07-28 relax prev to numeric/string conversion
1225 value will be the null string. Numeric and string conversions
003891a8 » TimToady
2012-07-28 Explication of lazy warnings
1226 use these lazy warnings to allow (but not require) failsoft semantics.
1227
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1228 =head1 The goto statement
0b2523c8 » szabgab
2009-04-29 add some X<> tags
1229 X<goto>
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1230
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
1231 In addition to C<next>, C<last>, and C<redo>, Perl 6 also supports
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1232 C<goto>. As with ordinary loop controls, the label is searched for
1233 first lexically within the current subroutine, then dynamically outside
1234 of it. Unlike with loop controls, however, scanning a scope includes
1235 a scan of any lexical scopes included within the current candidate
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
1236 scope. As in Perl 5, it is possible to C<goto> into a lexical scope,
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1237 but only for lexical scopes that require no special initialization
1238 of parameters. (Initialization of ordinary variables does not
1239 count--presumably the presence of a label will prevent code-movement
1240 optimizations past the label.) So, for instance, it's always possible
1241 to C<goto> into the next case of a C<when> or into either the "then"
1242 or "else" branch of a conditional. You may not go into a C<given>
1243 or a C<for>, though, because that would bypass a formal parameter
1244 binding (not to mention list generation in the case of C<for>).
888f27d7 » jdlugosz
2009-05-25 [s04] put in C<...> tags, fix some <...> that have the C missing, typ…
1245 (Note: the implicit default binding of an outer C<$_> to an inner C<$_>
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1246 can be emulated for a bare block, so that doesn't fall under the
1247 prohibition on bypassing formal binding.)
1248
187e15bc » TimToady
2011-08-23 document that forward goto requires quotes
1249 Because it is possible to go to a label that is after the operation,
1250 and because Perl 6 does one-pass passing, any C<goto> to a label
1251 that has not been yet declared (or is declared outside the outward
1252 lexical scope of the C<goto>) must enclose the label in quotes.
1253
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1254 =head1 Exceptions
1255
aca4e5d2 » TimToady
2011-07-08 detangling $! from inflight semantics of @!
1256 As in Perl 5, many built-in functions simply return an undefined value
1257 when you ask for a value out of range, or the function fails somehow.
5dfd9966 » TimToady
2012-07-28 resumable failures for coercions
1258 Perl 6 has C<Failure> objects, known as "unthrown exceptions" (though
1259 really a C<Failure> merely contains an unthrown exception), which
aca4e5d2 » TimToady
2011-07-08 detangling $! from inflight semantics of @!
1260 know whether they have been handled or not. C<$!> is a convenient
45ca8c8c » patch
2011-11-20 fix typos
1261 link to the last failure, and only ever contains one exception, the
aca4e5d2 » TimToady
2011-07-08 detangling $! from inflight semantics of @!
1262 most recent.
1263
1264 [Conjecture: all unhandled exceptions within a routine could be stored
1265 in C<@!>, with the most recent first. C<$!> would then be sugar for
1266 C<@![0]>. (Or we use push semantics and C<$!> means C<@![*-1]>.) This
1267 might be more robust than merely making C<@!> a parameter to CATCH.
1268 However, the new semantics of autothrowing when sink eats a Failure
1269 means we won't have many unthrown exceptions waiting around to be
1270 handled at the end of the block anymore. We should probably at least
1271 issue warnings, though, if the GC eventually collects a failure that
1272 was never handled. We can't really rely on end-of-routine cleanup
1273 to deal with failures that are returned as normal data, unless we go
1274 with the overhead of a lexical C<@!> variable.]
1275
1276 If you test a C<Failure> for C<.defined> or C<.Bool>, the C<Failure>
1277 marks itself as I<handled>; the exception acts as a
f36524d1 » lwall
2009-05-29 [S04] expand on C<$!> semantics, remove requirement for GC on block exit
1278 relatively harmless undefined value thereafter. Any other use of the
1279 C<Failure> object to extract a normal value will throw its associated
1280 exception immediately. (The C<Failure> may, however, be stored in
1281 any container whose type allows the C<Failure> role to be mixed in.)
1282 The C<.handled> method returns C<False> on failures that have not
1283 been handled. It returns C<True> for handled exceptions and for
e7a6479d » lwall
2009-11-24 much less tentatively go with the Mu suggestion from TheDamian++
1284 all non-C<Failure> objects. (That is, it is a C<Mu> method,
f36524d1 » lwall
2009-05-29 [S04] expand on C<$!> semantics, remove requirement for GC on block exit
1285 not a C<Failure> method. Only C<Failure> objects need to store the
1286 actual status however; other types just return C<True>.)
1287
1288 The C<.handled> method is C<rw>, so you may mark an exception as handled
1289 by assigning C<True> to it. Note however that
1290
1291 $!.handled = 1;
1292
aca4e5d2 » TimToady
2011-07-08 detangling $! from inflight semantics of @!
1293 marks only the last exception as handled. To mark them all as handled
1294 you must access them individually via the implicit loop of a CATCH block.
f36524d1 » lwall
2009-05-29 [S04] expand on C<$!> semantics, remove requirement for GC on block exit
1295
1296 A bare C<die>/C<fail> takes C<$!> as the default argument specifying
1297 the exception to be thrown or propagated outward to the caller's C<$!>.
1298
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1299 You can cause built-ins to automatically throw exceptions on failure using
1300
1301 use fatal;
1302
f36524d1 » lwall
2009-05-29 [S04] expand on C<$!> semantics, remove requirement for GC on block exit
1303 The C<fail> function responds to the caller's C<use fatal> state.
1304 It either returns an unthrown exception, or throws the exception.
ea2a0002 » jimmy
2009-08-07 [Spec]reverted \x20 to \xC2A0. "Perl 6" and "Perl 5" are words, so we…
1305 Before you get too happy about this pragma, note that Perl 6 contains
f36524d1 » lwall
2009-05-29 [S04] expand on C<$!> semantics, remove requirement for GC on block exit
1306 various parallel processing primitives that will tend to get blown
1307 up prematurely by thrown exceptions. Unthrown exceptions are meant
1308 to provide a failsoft mechanism in which failures can be treated
98b44aa6 » lwall
2009-05-29 [S04] typos
1309 as data and dealt with one by one, without aborting execution
f36524d1 » lwall
2009-05-29 [S04] expand on C<$!> semantics, remove requirement for GC on block exit
1310 of what may be perfectly valid parallel computations. If you
aca4e5d2 » TimToady
2011-07-08 detangling $! from inflight semantics of @!
1311 I<don't> deal with the failures as data, then sink context will
1312 automatically throw any unhandled C<Failure> that you try to discard.
f36524d1 » lwall
2009-05-29 [S04] expand on C<$!> semantics, remove requirement for GC on block exit
1313
1314 In any case, the overriding design principle here is that no
1315 unhandled exception is ever dropped on the floor, but propagated
aca4e5d2 » TimToady
2011-07-08 detangling $! from inflight semantics of @!
1316 outward until it is handled. If no explicit handler handles it,
1317 the implicit outermost exception handler will
1318 eventually decide to abort and print all unhandled exceptions passed
1319 in as its current C<@!> list.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1320
5dfd9966 » TimToady
2012-07-28 resumable failures for coercions
1321 It is possible to fail with a resumable exception, such as a warning.
1322 If the failure throws its exception and the exception resumes,
1323 the thrower by default returns the null string (C<''>) to whatever
1324 caused the failure to throw its exception. This may be overridden by
1325 attaching a C<.resume_value> to the warning. Hence numeric coercions
1326 such as C<+"42foo"> can be forced to return C<42> after issuing
1327 a warning.
1328
200d5c94 » lwall
2009-11-06 [S04] Set phasers to stun!
1329 =head1 Phasers
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1330
200d5c94 » lwall
2009-11-06 [S04] Set phasers to stun!
1331 A C<CATCH> block is just a trait of the closure containing it, and is
1332 automatically called at the appropriate moment. These auto-called
1333 blocks are known as I<phasers>, since they generally mark the
1334 transition from one phase of computing to another. For instance,
1335 a C<CHECK> block is called at the end of compiling a compilation
1336 unit. Other kinds of phasers can be installed as well; these are
1337 automatically called at various times as appropriate, and some of
1338 them respond to various control exceptions and exit values:
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1339
1340 BEGIN {...}* at compile time, ASAP, only ever runs once
1341 CHECK {...}* at compile time, ALAP, only ever runs once
1342 INIT {...}* at run time, ASAP, only ever runs once
1343 END {...} at run time, ALAP, only ever runs once
1344
1345 START {...}* on first ever execution, once per closure clone
1346
1347 ENTER {...}* at every block entry time, repeats on loop blocks.
504176f3 » lwall
2010-07-09 [S04] emphasize that LEAVE blocks *always* run even under stack unwin…
1348 LEAVE {...} at every block exit time (even stack unwinds from exceptions)
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1349 KEEP {...} at every successful block exit, part of LEAVE queue
1350 UNDO {...} at every unsuccessful block exit, part of LEAVE queue
1351
1352 FIRST {...}* at loop initialization time, before any ENTER
1353 NEXT {...} at loop continuation time, before any LEAVE
1354 LAST {...} at loop termination time, after any LEAVE
1355
1356 PRE {...} assert precondition at every block entry, before ENTER
1357 POST {...} assert postcondition at every block exit, after LEAVE
1358
1359 CATCH {...} catch exceptions, before LEAVE
1360 CONTROL {...} catch control exceptions, before LEAVE
1361
1362 Those marked with a C<*> can also be used within an expression:
1363
08f22a7b » Kodi Arfer
2010-09-07 Changed some references to (the now nonexistent) &localtime to use &n…
1364 my $compiletime = BEGIN { now };
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1365 our $temphandle = START { maketemp() };
1366
30daad18 » lwall
2009-07-04 [S04] allow certain value-producing blocks as statement prefixes
1367 As with other statement prefixes, these value-producing constructs
1368 may be placed in front of either a block or a statement:
1369
08f22a7b » Kodi Arfer
2010-09-07 Changed some references to (the now nonexistent) &localtime to use &n…
1370 my $compiletime = BEGIN now;
30daad18 » lwall
2009-07-04 [S04] allow certain value-producing blocks as statement prefixes
1371 our $temphandle = START maketemp();
1372
e23ae8cf » lwall
2009-11-12 [S04] liberalize phaser blorsts somewhat for more consistency, PerlJam++
1373 In fact, most of these phasers will take either a block or a statement
2249f91f » lwall
2009-11-19 [S04] as several folks have suggested, rename "blorst" to "blast"
1374 (known as a I<blast> in the vernacular). The statement form can be
1375 particularly useful to expose a lexically scoped
dff23644 » lwall
2009-11-20 [Spec] slaughter various confusing overloadings of the term 'context'
1376 declaration to the surrounding lexical scope without "trapping" it inside a block.
1377
1378 Hence these declare the same
30daad18 » lwall
2009-07-04 [S04] allow certain value-producing blocks as statement prefixes
1379 variables with the same scope as the preceding example, but run the
1380 statements as a whole at the indicated time:
1381
08f22a7b » Kodi Arfer
2010-09-07 Changed some references to (the now nonexistent) &localtime to use &n…
1382 BEGIN my $compiletime = now;
30daad18 » lwall
2009-07-04 [S04] allow certain value-producing blocks as statement prefixes
1383 START our $temphandle = maketemp();
1384
1385 (Note, however, that the value of a variable calculated at compile
1386 time may not persist under run-time cloning of any surrounding closure.)
1387
e23ae8cf » lwall
2009-11-12 [S04] liberalize phaser blorsts somewhat for more consistency, PerlJam++
1388 Most of the non-value-producing phasers may also be so used:
1389
1390 END say my $accumulator;
1391
1392 Note, however, that
1393
1394 END say my $accumulator = 0;
1395
1396 sets the variable to 0 at C<END> time, since that is when the "my"
1397 declaration is actually executed. Only argumentless phasers may
f80c769c » lwall
2009-11-24 [S04] clarifications suggested by TheDamian++
1398 use the statement form. This means that C<CATCH> and C<CONTROL>
e23ae8cf » lwall
2009-11-12 [S04] liberalize phaser blorsts somewhat for more consistency, PerlJam++
1399 always require a block, since they take an argument that sets C<$_>
f80c769c » lwall
2009-11-24 [S04] clarifications suggested by TheDamian++
1400 to the current topic, so that the innards are able to behave
1401 as a switch statement. (If bare statements were allowed, the
1402 temporary binding of C<$_> would leak out past the end of the C<CATCH>
1403 or C<CONTROL>, with unpredictable and quite possibly dire consequences.
1404 Exception handlers are supposed to reduce uncertainty, not increase it.)
e23ae8cf » lwall
2009-11-12 [S04] liberalize phaser blorsts somewhat for more consistency, PerlJam++
1405
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1406 Code that is generated at run time can still fire off C<CHECK>
200d5c94 » lwall
2009-11-06 [S04] Set phasers to stun!
1407 and C<INIT> phasers, though of course those phasers can't do things that
1408 would require travel back in time. You need a wormhole for that.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1409
200d5c94 » lwall
2009-11-06 [S04] Set phasers to stun!
1410 Some of these phasers also have corresponding traits that can be set on variables.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1411 These have the advantage of passing the variable in question into
1412 the closure as its topic:
1413
1414 my $r will start { .set_random_seed() };
1415 our $h will enter { .rememberit() } will undo { .forgetit() };
1416
1417 Apart from C<CATCH> and C<CONTROL>, which can only occur once, most
1418 of these can occur multiple times within the block. So they aren't
1419 really traits, exactly--they add themselves onto a list stored in the
1420 actual trait (except for C<START>, which executes inline). So if you
1421 examine the C<ENTER> trait of a block, you'll find that it's really
59b0ea5b » Util
2011-11-12 Fix typos.
1422 a list of phasers rather than a single phaser. In general, initializing
7812d5d3 » TimToady
2012-03-18 small typo
1423 phasers execute in order declared, while finalizing phasers execute in
c4932277 » TimToady
2011-07-31 define normal order for init vs final phasers
1424 the opposite order.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1425
1426 The semantics of C<INIT> and C<START> are not equivalent to each
1427 other in the case of cloned closures. An C<INIT> only runs once for
1428 all copies of a cloned closure. A C<START> runs separately for each
1429 clone, so separate clones can keep separate state variables:
1430
1431 our $i = 0;
1432 ...
1433 $func = { state $x will start { $x = $i++ }; dostuff($i) };
1434
1435 But C<state> automatically applies "start" semantics to any initializer,
1436 so this also works:
1437
1438 $func = { state $x = $i++; dostuff($i) }
1439
1440 Each subsequent clone gets an initial state that is one higher than the
1441 previous, and each clone maintains its own state of C<$x>, because that's
1442 what C<state> variables do.
1443
1444 Even in the absence of closure cloning, C<INIT> runs before the
1445 mainline code, while C<START> puts off the initialization till the
1446 last possible moment, then runs exactly once, and caches its value
b193100e » lwall
2009-11-20 [S02,3,4] attempt to rename void context to sink context and see if i…
1447 for all subsequent calls (assuming it wasn't called in sink context,
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1448 in which case the C<START> is evaluated once only for its side effects).
1449 In particular, this means that C<START> can make use of any parameters
1450 passed in on the first call, whereas C<INIT> cannot.
1451
200d5c94 » lwall
2009-11-06 [S04] Set phasers to stun!
1452 All of these phaser blocks can see any previously declared lexical
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1453 variables, even if those variables have not been elaborated yet when
1454 the closure is invoked (in which case the variables evaluate to an
1455 undefined value.)
1456
1457 Note: Apocalypse 4 confused the notions of C<PRE>/C<POST> with C<ENTER>/C<LEAVE>.
1458 These are now separate notions. C<ENTER> and C<LEAVE> are used only for
578e3cbf » masak
2012-03-11 [S04] un-spec method-level PRE/POST
1459 their side effects. C<PRE> and C<POST> return boolean values which, if
1460 false, trigger a runtime exception. C<KEEP> and C<UNDO> are just variants
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1461 of C<LEAVE>, and for execution order are treated as part of the queue of
200d5c94 » lwall
2009-11-06 [S04] Set phasers to stun!
1462 C<LEAVE> phasers.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1463
937f37f7 » masak
2012-03-11 [S04] unspec submethod PRE/POST
1464 It is conjectured that C<PRE> and C<POST> submethods in a class could be
1465 made to run as if they were phasers in any public method of the class.
1466 This feature is awaiting further exploration by means of a C<ClassHOW>
1467 extension.
1468
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1469 C<FIRST>, C<NEXT>, and C<LAST> are meaningful only within the
1470 lexical scope of a loop, and may occur only at the top level of such
1471 a loop block. A C<NEXT> executes only if the end of the loop block is
1472 reached normally, or an explicit C<next> is executed. In distinction
200d5c94 » lwall
2009-11-06 [S04] Set phasers to stun!
1473 to C<LEAVE> phasers, a C<NEXT> phaser is not executed if the loop block
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1474 is exited via any exception other than the control exception thrown
1475 by C<next>. In particular, a C<last> bypasses evaluation of C<NEXT>
200d5c94 » lwall
2009-11-06 [S04] Set phasers to stun!
1476 phasers.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1477
1478 [Note: the name C<FIRST> used to be associated with C<state>
1479 declarations. Now it is associated only with loops. See the C<START>
1480 above for C<state> semantics.]
1481
a359f095 » lwall
2010-02-17 [S04] clarify that leave phasers do not trip till after an exception …
1482 Except for C<CATCH> and C<CONTROL> phasers, which run while an exception
1483 is looking for a place to handle it, all block-leaving phasers wait until
15be004b » lwall
2010-02-18 [S04] unmuddying requested by Richard Hainsworth++
1484 the call stack is actually unwound to run. Unwinding happens only after
1485 some exception handler decides to handle the exception that way. That is,
1486 just because an exception is thrown past a stack frame does not mean we have
1487 officially left the block yet, since the exception might be resumable. In
1488 any case, exception handlers are specified to run within the dynamic scope
1489 of the failing code, whether or not the exception is resumable. The stack
1490 is unwound and the phasers are called only if an exception is not resumed.
a359f095 » lwall
2010-02-17 [S04] clarify that leave phasers do not trip till after an exception …
1491
1492 So C<LEAVE> phasers for a given block are necessarily evaluated after
1493 any C<CATCH> and C<CONTROL> phasers. This includes
200d5c94 » lwall
2009-11-06 [S04] Set phasers to stun!
1494 the C<LEAVE> variants, C<KEEP> and C<UNDO>. C<POST> phasers are evaluated after
578e3cbf » masak
2012-03-11 [S04] un-spec method-level PRE/POST
1495 everything else, to guarantee that even C<LEAVE> phasers can't violate postconditions.
200d5c94 » lwall
2009-11-06 [S04] Set phasers to stun!
1496 Likewise C<PRE> phasers fire off before any C<ENTER> or C<FIRST> (though not
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1497 before C<BEGIN>, C<CHECK>, or C<INIT>, since those are done at compile or
937f37f7 » masak
2012-03-11 [S04] unspec submethod PRE/POST
1498 process initialization time).
578e3cbf » masak
2012-03-11 [S04] un-spec method-level PRE/POST
1499
1500 The C<POST> block can be defined in one of two ways. Either the
937f37f7 » masak
2012-03-11 [S04] unspec submethod PRE/POST
1501 corresponding C<POST> is defined as a separate phaser,
578e3cbf » masak
2012-03-11 [S04] un-spec method-level PRE/POST
1502 in which case C<PRE> and C<POST> share no lexical scope.
1503 Alternately, any C<PRE>
937f37f7 » masak
2012-03-11 [S04] unspec submethod PRE/POST
1504 phaser may define its corresponding C<POST>
4dbbc16d » lwall
2010-07-09 [S04,6] more refinement of how scoping works under DBC
1505 as an embedded phaser block that closes over the lexical scope of
578e3cbf » masak
2012-03-11 [S04] un-spec method-level PRE/POST
1506 the C<PRE>.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1507
aca4e5d2 » TimToady
2011-07-08 detangling $! from inflight semantics of @!
1508 If exit phasers are running as a result of a stack unwind initiated by
1509 an exception, this information needs to be made available. In any
1510 case, the information as to whether the block is being exited
1511 successfully or unsuccessfully needs to be available to decide
1512 whether to run C<KEEP> or C<UNDO> blocks. How this information is
1513 made available is implementation dependent.
cd30d2ee » benmorrow
2009-08-16 [Spec] Clarify behaviour of closure traits when an exception is thrown.
1514
200d5c94 » lwall
2009-11-06 [S04] Set phasers to stun!
1515 An exception thrown from an C<ENTER> phaser will abort the C<ENTER>
1516 queue, but one thrown from a C<LEAVE> phaser will not. The exceptions
1517 thrown by failing C<PRE> and C<POST> phasers cannot be caught by a
1518 C<CATCH> in the same block, which implies that C<POST> phaser are not
aca4e5d2 » TimToady
2011-07-08 detangling $! from inflight semantics of @!
1519 run if a C<PRE> phaser fails.
1520
1521 If a C<POST> fails or any kind of C<LEAVE> block throws an exception
1522 while the stack is unwinding, the unwinding continues and collects
1523 exceptions to be handled. When the unwinding is completed all new
1524 exceptions are thrown from that point.
cd30d2ee » benmorrow
2009-08-16 [Spec] Clarify behaviour of closure traits when an exception is thrown.
1525
200d5c94 » lwall
2009-11-06 [S04] Set phasers to stun!
1526 For phasers such as C<KEEP> and C<POST> that are run when exiting a
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1527 scope normally, the return value (if any) from that scope is available
3a683f84 » lwall
2010-02-17 [S02,S04] more clarification of when parcels are and aren't used.
1528 as the current topic within the phaser. (It is presented as a argument,
1529 that is, either as parcel or an object that can stand alone in a list.
1530 In other words, it's exactly what C<return> is sending to the outside
1531 world in raw form, so that the phaser doesn't accidentally impose
1532 context prematurely.)
1533
4dbbc16d » lwall
2010-07-09 [S04,6] more refinement of how scoping works under DBC
1534 The topic of the block outside a phaser is still available as C<< OUTER::<$_> >>.
200d5c94 » lwall
2009-11-06 [S04] Set phasers to stun!
1535 Whether the return value is modifiable may be a policy of the phaser
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1536 in question. In particular, the return value should not be modified
200d5c94 » lwall
2009-11-06 [S04] Set phasers to stun!
1537 within a C<POST> phaser, but a C<LEAVE> phaser could be more liberal.
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1538
4dbbc16d » lwall
2010-07-09 [S04,6] more refinement of how scoping works under DBC
1539 Any phaser defined in the lexical scope of a method is a closure that
1540 closes over C<self> as well as normal lexicals. (Or equivalently,
1541 an implementation may simply turn all such phasers into submethods
d1124cfe » TimToady
2011-10-06 s/currying/priming/
1542 whose primed invocant is the current object.)
30667101 » lwall
2010-07-09 [S04] simplify definition of successful return to be context agnostic
1543
68d062fc » pmichaud
2008-11-26 Move synopses to their new home.
1544 =head1 Statement parsing
1545