Debian Codegraph @

upstream/debian-unstable/man1/perlsyn.1

raw
1 .\" -*- mode: troff; coding: utf-8 -*-
2 .\" Automatically generated by Pod::Man 5.0102 (Pod::Simple 3.45)
3 .\"
4 .\" Standard preamble:
5 .\" ========================================================================
6 .de Sp \" Vertical space (when we can't use .PP)
7 .if t .sp .5v
8 .if n .sp
9 ..
10 .de Vb \" Begin verbatim text
11 .ft CW
12 .nf
13 .ne \\$1
14 ..
15 .de Ve \" End verbatim text
16 .ft R
17 .fi
18 ..
19 .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>.
20 .ie n \{\
21 . ds C` ""
22 . ds C' ""
23 'br\}
24 .el\{\
25 . ds C`
26 . ds C'
27 'br\}
28 .\"
29 .\" Escape single quotes in literal strings from groff's Unicode transform.
30 .ie \n(.g .ds Aq \(aq
31 .el .ds Aq '
32 .\"
33 .\" If the F register is >0, we'll generate index entries on stderr for
34 .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
35 .\" entries marked with X<> in POD. Of course, you'll have to process the
36 .\" output yourself in some meaningful fashion.
37 .\"
38 .\" Avoid warning from groff about undefined register 'F'.
39 .de IX
40 ..
41 .nr rF 0
42 .if \n(.g .if rF .nr rF 1
43 .if (\n(rF:(\n(.g==0)) \{\
44 . if \nF \{\
45 . de IX
46 . tm Index:\\$1\t\\n%\t"\\$2"
47 ..
48 . if !\nF==2 \{\
49 . nr % 0
50 . nr F 2
51 . \}
52 . \}
53 .\}
54 .rr rF
55 .\" ========================================================================
56 .\"
57 .IX Title "PERLSYN 1"
58 .TH PERLSYN 1 2025-11-16 "perl v5.40.1" "Perl Programmers Reference Guide"
59 .\" For nroff, turn off justification. Always turn off hyphenation; it makes
60 .\" way too many mistakes in technical documents.
61 .if n .ad l
62 .nh
63 .SH NAME
64 perlsyn \- Perl syntax: declarations, statements, comments
65 .IX Xref "syntax"
66 .SH DESCRIPTION
67 .IX Header "DESCRIPTION"
68 A Perl program consists of a sequence of declarations and statements
69 which run from the top to the bottom. Loops, subroutines, and other
70 control structures allow you to jump around within the code.
71 .PP
72 Perl is a \fBfree-form\fR language: you can format and indent it however
73 you like. Whitespace serves mostly to separate tokens, unlike
74 languages like Python where it is an important part of the syntax,
75 or Fortran where it is immaterial.
76 .PP
77 Many of Perl's syntactic elements are \fBoptional\fR. Rather than
78 requiring you to put parentheses around every function call and
79 declare every variable, you can often leave such explicit elements off
80 and Perl will figure out what you meant. This is known as \fBDo What I
81 Mean\fR, abbreviated \fBDWIM\fR. It allows programmers to be \fBlazy\fR and to
82 code in a style with which they are comfortable.
83 .PP
84 Perl \fBborrows syntax\fR and concepts from many languages: awk, sed, C,
85 Bourne Shell, Smalltalk, Lisp and even English. Other
86 languages have borrowed syntax from Perl, particularly its regular
87 expression extensions. So if you have programmed in another language
88 you will see familiar pieces in Perl. They often work the same, but
89 see perltrap for information about how they differ.
90 .SS Declarations
91 .IX Xref "declaration undef undefined uninitialized"
92 .IX Subsection "Declarations"
93 The only things you need to declare in Perl are report formats and
94 subroutines (and sometimes not even subroutines). A scalar variable holds
95 the undefined value (\f(CW\*(C`undef\*(C'\fR) until it has been assigned a defined
96 value, which is anything other than \f(CW\*(C`undef\*(C'\fR. When used as a number,
97 \&\f(CW\*(C`undef\*(C'\fR is treated as \f(CW0\fR; when used as a string, it is treated as
98 the empty string, \f(CW""\fR; and when used as a reference that isn't being
99 assigned to, it is treated as an error. If you enable warnings,
100 you'll be notified of an uninitialized value whenever you treat
101 \&\f(CW\*(C`undef\*(C'\fR as a string or a number. Well, usually. Boolean contexts,
102 such as:
103 .PP
104 .Vb 1
105 \& if ($x) {}
106 .Ve
107 .PP
108 are exempt from warnings (because they care about truth rather than
109 definedness). Operators such as \f(CW\*(C`++\*(C'\fR, \f(CW\*(C`\-\-\*(C'\fR, \f(CW\*(C`+=\*(C'\fR,
110 \&\f(CW\*(C`\-=\*(C'\fR, and \f(CW\*(C`.=\*(C'\fR, that operate on undefined variables such as:
111 .PP
112 .Vb 2
113 \& undef $x;
114 \& $x++;
115 .Ve
116 .PP
117 are also always exempt from such warnings.
118 .PP
119 A declaration can be put anywhere a statement can, but has no effect on
120 the execution of the primary sequence of statements: declarations all
121 take effect at compile time. All declarations are typically put at
122 the beginning or the end of the script. However, if you're using
123 lexically-scoped private variables created with \f(CWmy()\fR,
124 \&\f(CWstate()\fR, or \f(CWour()\fR, you'll have to make sure
125 your format or subroutine definition is within the same block scope
126 as the my if you expect to be able to access those private variables.
127 .PP
128 Declaring a subroutine allows a subroutine name to be used as if it were a
129 list operator from that point forward in the program. You can declare a
130 subroutine without defining it by saying \f(CW\*(C`sub name\*(C'\fR, thus:
131 .IX Xref "subroutine, declaration"
132 .PP
133 .Vb 2
134 \& sub myname;
135 \& $me = myname $0 or die "can\*(Aqt get myname";
136 .Ve
137 .PP
138 A bare declaration like that declares the function to be a list operator,
139 not a unary operator, so you have to be careful to use parentheses (or
140 \&\f(CW\*(C`or\*(C'\fR instead of \f(CW\*(C`||\*(C'\fR.) The \f(CW\*(C`||\*(C'\fR operator binds too tightly to use after
141 list operators; it becomes part of the last element. You can always use
142 parentheses around the list operators arguments to turn the list operator
143 back into something that behaves more like a function call. Alternatively,
144 you can use the prototype \f(CW\*(C`($)\*(C'\fR to turn the subroutine into a unary
145 operator:
146 .PP
147 .Vb 2
148 \& sub myname ($);
149 \& $me = myname $0 || die "can\*(Aqt get myname";
150 .Ve
151 .PP
152 That now parses as you'd expect, but you still ought to get in the habit of
153 using parentheses in that situation. For more on prototypes, see
154 perlsub.
155 .PP
156 Subroutines declarations can also be loaded up with the \f(CW\*(C`require\*(C'\fR statement
157 or both loaded and imported into your namespace with a \f(CW\*(C`use\*(C'\fR statement.
158 See perlmod for details on this.
159 .PP
160 A statement sequence may contain declarations of lexically-scoped
161 variables, but apart from declaring a variable name, the declaration acts
162 like an ordinary statement, and is elaborated within the sequence of
163 statements as if it were an ordinary statement. That means it actually
164 has both compile-time and run-time effects.
165 .SS Comments
166 .IX Xref "comment #"
167 .IX Subsection "Comments"
168 Text from a \f(CW"#"\fR character until the end of the line is a comment,
169 and is ignored. Exceptions include \f(CW"#"\fR inside a string or regular
170 expression.
171 .SS "Simple Statements"
172 .IX Xref "statement semicolon expression ;"
173 .IX Subsection "Simple Statements"
174 The only kind of simple statement is an expression evaluated for its
175 side-effects. Every simple statement must be terminated with a
176 semicolon, unless it is the final statement in a block, in which case
177 the semicolon is optional. But put the semicolon in anyway if the
178 block takes up more than one line, because you may eventually add
179 another line. Note that there are operators like \f(CW\*(C`eval {}\*(C'\fR, \f(CW\*(C`sub {}\*(C'\fR, and
180 \&\f(CW\*(C`do {}\*(C'\fR that \fIlook\fR like compound statements, but aren't\-\-they're just
181 TERMs in an expression\-\-and thus need an explicit termination when used
182 as the last item in a statement.
183 .SS "Statement Modifiers"
184 .IX Xref "statement modifier modifier if unless while until when foreach for"
185 .IX Subsection "Statement Modifiers"
186 Any simple statement may optionally be followed by a \fISINGLE\fR modifier,
187 just before the terminating semicolon (or block ending). The possible
188 modifiers are:
189 .PP
190 .Vb 7
191 \& if EXPR
192 \& unless EXPR
193 \& while EXPR
194 \& until EXPR
195 \& for LIST
196 \& foreach LIST
197 \& when EXPR
198 .Ve
199 .PP
200 The \f(CW\*(C`EXPR\*(C'\fR following the modifier is referred to as the "condition".
201 Its truth or falsehood determines how the modifier will behave.
202 .PP
203 \&\f(CW\*(C`if\*(C'\fR executes the statement once \fIif\fR and only if the condition is
204 true. \f(CW\*(C`unless\*(C'\fR is the opposite, it executes the statement \fIunless\fR
205 the condition is true (that is, if the condition is false). See
206 "Scalar values" in perldata for definitions of true and false.
207 .PP
208 .Vb 2
209 \& print "Basset hounds got long ears" if length $ear >= 10;
210 \& go_outside() and play() unless $is_raining;
211 .Ve
212 .PP
213 The \f(CWfor(each)\fR modifier is an iterator: it executes the statement once
214 for each item in the LIST (with \f(CW$_\fR aliased to each item in turn).
215 There is no syntax to specify a C\-style for loop or a lexically scoped
216 iteration variable in this form.
217 .PP
218 .Vb 1
219 \& print "Hello $_!\en" for qw(world Dolly nurse);
220 .Ve
221 .PP
222 \&\f(CW\*(C`while\*(C'\fR repeats the statement \fIwhile\fR the condition is true.
223 Postfix \f(CW\*(C`while\*(C'\fR has the same magic treatment of some kinds of condition
224 that prefix \f(CW\*(C`while\*(C'\fR has.
225 \&\f(CW\*(C`until\*(C'\fR does the opposite, it repeats the statement \fIuntil\fR the
226 condition is true (or while the condition is false):
227 .PP
228 .Vb 3
229 \& # Both of these count from 0 to 10.
230 \& print $i++ while $i <= 10;
231 \& print $j++ until $j > 10;
232 .Ve
233 .PP
234 The \f(CW\*(C`while\*(C'\fR and \f(CW\*(C`until\*(C'\fR modifiers have the usual "\f(CW\*(C`while\*(C'\fR loop"
235 semantics (conditional evaluated first), except when applied to a
236 \&\f(CW\*(C`do\*(C'\fR\-BLOCK (or to the Perl4 \f(CW\*(C`do\*(C'\fR\-SUBROUTINE statement), in
237 which case the block executes once before the conditional is
238 evaluated.
239 .PP
240 This is so that you can write loops like:
241 .PP
242 .Vb 4
243 \& do {
244 \& $line = <STDIN>;
245 \& ...
246 \& } until !defined($line) || $line eq ".\en"
247 .Ve
248 .PP
249 See "do" in perlfunc. Note also that the loop control statements described
250 later will \fINOT\fR work in this construct, because modifiers don't take
251 loop labels. Sorry. You can always put another block inside of it
252 (for \f(CW\*(C`next\*(C'\fR/\f(CW\*(C`redo\*(C'\fR) or around it (for \f(CW\*(C`last\*(C'\fR) to do that sort of thing.
253 .IX Xref "next last redo"
254 .PP
255 For \f(CW\*(C`next\*(C'\fR or \f(CW\*(C`redo\*(C'\fR, just double the braces:
256 .PP
257 .Vb 4
258 \& do {{
259 \& next if $x == $y;
260 \& # do something here
261 \& }} until $x++ > $z;
262 .Ve
263 .PP
264 For \f(CW\*(C`last\*(C'\fR, you have to be more elaborate and put braces around it:
265 .IX Xref "last"
266 .PP
267 .Vb 6
268 \& {
269 \& do {
270 \& last if $x == $y**2;
271 \& # do something here
272 \& } while $x++ <= $z;
273 \& }
274 .Ve
275 .PP
276 If you need both \f(CW\*(C`next\*(C'\fR and \f(CW\*(C`last\*(C'\fR, you have to do both and also use a
277 loop label:
278 .PP
279 .Vb 7
280 \& LOOP: {
281 \& do {{
282 \& next if $x == $y;
283 \& last LOOP if $x == $y**2;
284 \& # do something here
285 \& }} until $x++ > $z;
286 \& }
287 .Ve
288 .PP
289 \&\fBNOTE:\fR The behaviour of a \f(CW\*(C`my\*(C'\fR, \f(CW\*(C`state\*(C'\fR, or
290 \&\f(CW\*(C`our\*(C'\fR modified with a statement modifier conditional
291 or loop construct (for example, \f(CW\*(C`my $x if ...\*(C'\fR) is
292 \&\fBundefined\fR. The value of the \f(CW\*(C`my\*(C'\fR variable may be \f(CW\*(C`undef\*(C'\fR, any
293 previously assigned value, or possibly anything else. Don't rely on
294 it. Future versions of perl might do something different from the
295 version of perl you try it out on. Here be dragons.
296 .IX Xref "my"
297 .PP
298 The \f(CW\*(C`when\*(C'\fR modifier is an experimental feature that first appeared in Perl
299 5.14. To use it, you should include a \f(CW\*(C`use v5.14\*(C'\fR declaration.
300 (Technically, it requires only the \f(CW\*(C`switch\*(C'\fR feature, but that aspect of it
301 was not available before 5.14.) Operative only from within a \f(CW\*(C`foreach\*(C'\fR
302 loop or a \f(CW\*(C`given\*(C'\fR block, it executes the statement only if the smartmatch
303 \&\f(CW\*(C`$_ ~~ \fR\f(CIEXPR\fR\f(CW\*(C'\fR is true. If the statement executes, it is followed by
304 a \f(CW\*(C`next\*(C'\fR from inside a \f(CW\*(C`foreach\*(C'\fR and \f(CW\*(C`break\*(C'\fR from inside a \f(CW\*(C`given\*(C'\fR.
305 .PP
306 Under the current implementation, the \f(CW\*(C`foreach\*(C'\fR loop can be
307 anywhere within the \f(CW\*(C`when\*(C'\fR modifier's dynamic scope, but must be
308 within the \f(CW\*(C`given\*(C'\fR block's lexical scope. This restriction may
309 be relaxed in a future release. See "Switch Statements" below.
310 .SS "Compound Statements"
311 .IX Xref "statement, compound block bracket, curly curly bracket brace { } if unless given while until foreach for continue"
312 .IX Subsection "Compound Statements"
313 In Perl, a sequence of statements that defines a scope is called a block.
314 Sometimes a block is delimited by the file containing it (in the case
315 of a required file, or the program as a whole), and sometimes a block
316 is delimited by the extent of a string (in the case of an eval).
317 .PP
318 But generally, a block is delimited by curly brackets, also known as
319 braces. We will call this syntactic construct a BLOCK. Because enclosing
320 braces are also the syntax for hash reference constructor expressions
321 (see perlref), you may occasionally need to disambiguate by placing a
322 \&\f(CW\*(C`;\*(C'\fR immediately after an opening brace so that Perl realises the brace
323 is the start of a block. You will more frequently need to disambiguate
324 the other way, by placing a \f(CW\*(C`+\*(C'\fR immediately before an opening brace to
325 force it to be interpreted as a hash reference constructor expression.
326 It is considered good style to use these disambiguating mechanisms
327 liberally, not only when Perl would otherwise guess incorrectly.
328 .PP
329 The following compound statements may be used to control flow:
330 .PP
331 .Vb 4
332 \& if (EXPR) BLOCK
333 \& if (EXPR) BLOCK else BLOCK
334 \& if (EXPR) BLOCK elsif (EXPR) BLOCK ...
335 \& if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
336 \&
337 \& unless (EXPR) BLOCK
338 \& unless (EXPR) BLOCK else BLOCK
339 \& unless (EXPR) BLOCK elsif (EXPR) BLOCK ...
340 \& unless (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
341 \&
342 \& given (EXPR) BLOCK
343 \&
344 \& LABEL while (EXPR) BLOCK
345 \& LABEL while (EXPR) BLOCK continue BLOCK
346 \&
347 \& LABEL until (EXPR) BLOCK
348 \& LABEL until (EXPR) BLOCK continue BLOCK
349 \&
350 \& LABEL for (EXPR; EXPR; EXPR) BLOCK
351 \& LABEL for VAR (LIST) BLOCK
352 \& LABEL for VAR (LIST) BLOCK continue BLOCK
353 \&
354 \& LABEL foreach (EXPR; EXPR; EXPR) BLOCK
355 \& LABEL foreach VAR (LIST) BLOCK
356 \& LABEL foreach VAR (LIST) BLOCK continue BLOCK
357 \&
358 \& LABEL BLOCK
359 \& LABEL BLOCK continue BLOCK
360 \&
361 \& PHASE BLOCK
362 .Ve
363 .PP
364 As of Perl 5.36, you can iterate over multiple values at a time by specifying
365 a list of lexicals within parentheses:
366 .PP
367 .Vb 4
368 \& LABEL for my (VAR, VAR) (LIST) BLOCK
369 \& LABEL for my (VAR, VAR) (LIST) BLOCK continue BLOCK
370 \& LABEL foreach my (VAR, VAR) (LIST) BLOCK
371 \& LABEL foreach my (VAR, VAR) (LIST) BLOCK continue BLOCK
372 .Ve
373 .PP
374 If enabled by the \f(CW\*(C`try\*(C'\fR feature, the following may also be used
375 .PP
376 .Vb 2
377 \& try BLOCK catch (VAR) BLOCK
378 \& try BLOCK catch (VAR) BLOCK finally BLOCK
379 .Ve
380 .PP
381 The experimental \f(CW\*(C`given\*(C'\fR statement is \fInot automatically enabled\fR; see
382 "Switch Statements" below for how to do so, and the attendant caveats.
383 .PP
384 Unlike in C and Pascal, in Perl these are all defined in terms of BLOCKs,
385 not statements. This means that the curly brackets are \fIrequired\fR\-\-no
386 dangling statements allowed. If you want to write conditionals without
387 curly brackets, there are several other ways to do it. The following
388 all do the same thing:
389 .PP
390 .Vb 5
391 \& if (!open(FOO)) { die "Can\*(Aqt open $FOO: $!" }
392 \& die "Can\*(Aqt open $FOO: $!" unless open(FOO);
393 \& open(FOO) || die "Can\*(Aqt open $FOO: $!";
394 \& open(FOO) ? () : die "Can\*(Aqt open $FOO: $!";
395 \& # a bit exotic, that last one
396 .Ve
397 .PP
398 The \f(CW\*(C`if\*(C'\fR statement is straightforward. Because BLOCKs are always
399 bounded by curly brackets, there is never any ambiguity about which
400 \&\f(CW\*(C`if\*(C'\fR an \f(CW\*(C`else\*(C'\fR goes with. If you use \f(CW\*(C`unless\*(C'\fR in place of \f(CW\*(C`if\*(C'\fR,
401 the sense of the test is reversed. Like \f(CW\*(C`if\*(C'\fR, \f(CW\*(C`unless\*(C'\fR can be followed
402 by \f(CW\*(C`else\*(C'\fR. \f(CW\*(C`unless\*(C'\fR can even be followed by one or more \f(CW\*(C`elsif\*(C'\fR
403 statements, though you may want to think twice before using that particular
404 language construct, as everyone reading your code will have to think at least
405 twice before they can understand what's going on.
406 .PP
407 The \f(CW\*(C`while\*(C'\fR statement executes the block as long as the expression is
408 true.
409 The \f(CW\*(C`until\*(C'\fR statement executes the block as long as the expression is
410 false.
411 The LABEL is optional, and if present, consists of an identifier followed
412 by a colon. The LABEL identifies the loop for the loop control
413 statements \f(CW\*(C`next\*(C'\fR, \f(CW\*(C`last\*(C'\fR, and \f(CW\*(C`redo\*(C'\fR.
414 If the LABEL is omitted, the loop control statement
415 refers to the innermost enclosing loop. This may include dynamically
416 searching through your call-stack at run time to find the LABEL. Such
417 desperate behavior triggers a warning if you use the \f(CW\*(C`use warnings\*(C'\fR
418 pragma or the \fB\-w\fR flag.
419 .PP
420 If the condition expression of a \f(CW\*(C`while\*(C'\fR statement is based
421 on any of a group of iterative expression types then it gets
422 some magic treatment. The affected iterative expression types
423 are \f(CW\*(C`readline\*(C'\fR, the \f(CW\*(C`<FILEHANDLE>\*(C'\fR input operator, \f(CW\*(C`readdir\*(C'\fR, \f(CW\*(C`glob\*(C'\fR, the \f(CW\*(C`<PATTERN>\*(C'\fR globbing operator, and \f(CW\*(C`each\*(C'\fR. If the condition expression is one of these expression types, then
424 the value yielded by the iterative operator will be implicitly assigned
425 to \f(CW$_\fR. If the condition expression is one of these expression types
426 or an explicit assignment of one of them to a scalar, then the condition
427 actually tests for definedness of the expression's value, not for its
428 regular truth value.
429 .PP
430 If there is a \f(CW\*(C`continue\*(C'\fR BLOCK, it is always executed just before the
431 conditional is about to be evaluated again. Thus it can be used to
432 increment a loop variable, even when the loop has been continued via
433 the \f(CW\*(C`next\*(C'\fR statement.
434 .PP
435 When a block is preceded by a compilation phase keyword such as \f(CW\*(C`BEGIN\*(C'\fR,
436 \&\f(CW\*(C`END\*(C'\fR, \f(CW\*(C`INIT\*(C'\fR, \f(CW\*(C`CHECK\*(C'\fR, or \f(CW\*(C`UNITCHECK\*(C'\fR, then the block will run only
437 during the corresponding phase of execution. See perlmod for more details.
438 .PP
439 Extension modules can also hook into the Perl parser to define new
440 kinds of compound statements. These are introduced by a keyword which
441 the extension recognizes, and the syntax following the keyword is
442 defined entirely by the extension. If you are an implementor, see
443 "PL_keyword_plugin" in perlapi for the mechanism. If you are using such
444 a module, see the module's documentation for details of the syntax that
445 it defines.
446 .SS "Loop Control"
447 .IX Xref "loop control loop, control next last redo continue"
448 .IX Subsection "Loop Control"
449 The \f(CW\*(C`next\*(C'\fR command starts the next iteration of the loop:
450 .PP
451 .Vb 4
452 \& LINE: while (<STDIN>) {
453 \& next LINE if /^#/; # discard comments
454 \& ...
455 \& }
456 .Ve
457 .PP
458 The \f(CW\*(C`last\*(C'\fR command immediately exits the loop in question. The
459 \&\f(CW\*(C`continue\*(C'\fR block, if any, is not executed:
460 .PP
461 .Vb 4
462 \& LINE: while (<STDIN>) {
463 \& last LINE if /^$/; # exit when done with header
464 \& ...
465 \& }
466 .Ve
467 .PP
468 The \f(CW\*(C`redo\*(C'\fR command restarts the loop block without evaluating the
469 conditional again. The \f(CW\*(C`continue\*(C'\fR block, if any, is \fInot\fR executed.
470 This command is normally used by programs that want to lie to themselves
471 about what was just input.
472 .PP
473 For example, when processing a file like \fI/etc/termcap\fR.
474 If your input lines might end in backslashes to indicate continuation, you
475 want to skip ahead and get the next record.
476 .PP
477 .Vb 8
478 \& while (<>) {
479 \& chomp;
480 \& if (s/\e\e$//) {
481 \& $_ .= <>;
482 \& redo unless eof();
483 \& }
484 \& # now process $_
485 \& }
486 .Ve
487 .PP
488 which is Perl shorthand for the more explicitly written version:
489 .PP
490 .Vb 8
491 \& LINE: while (defined($line = <ARGV>)) {
492 \& chomp($line);
493 \& if ($line =~ s/\e\e$//) {
494 \& $line .= <ARGV>;
495 \& redo LINE unless eof(); # not eof(ARGV)!
496 \& }
497 \& # now process $line
498 \& }
499 .Ve
500 .PP
501 Note that if there were a \f(CW\*(C`continue\*(C'\fR block on the above code, it would
502 get executed only on lines discarded by the regex (since redo skips the
503 continue block). A continue block is often used to reset line counters
504 or \f(CW\*(C`m?pat?\*(C'\fR one-time matches:
505 .PP
506 .Vb 10
507 \& # inspired by :1,$g/fred/s//WILMA/
508 \& while (<>) {
509 \& m?(fred)? && s//WILMA $1 WILMA/;
510 \& m?(barney)? && s//BETTY $1 BETTY/;
511 \& m?(homer)? && s//MARGE $1 MARGE/;
512 \& } continue {
513 \& print "$ARGV $.: $_";
514 \& close ARGV if eof; # reset $.
515 \& reset if eof; # reset ?pat?
516 \& }
517 .Ve
518 .PP
519 If the word \f(CW\*(C`while\*(C'\fR is replaced by the word \f(CW\*(C`until\*(C'\fR, the sense of the
520 test is reversed, but the conditional is still tested before the first
521 iteration.
522 .PP
523 Loop control statements don't work in an \f(CW\*(C`if\*(C'\fR or \f(CW\*(C`unless\*(C'\fR, since
524 they aren't loops. You can double the braces to make them such, though.
525 .PP
526 .Vb 6
527 \& if (/pattern/) {{
528 \& last if /fred/;
529 \& next if /barney/; # same effect as "last",
530 \& # but doesn\*(Aqt document as well
531 \& # do something here
532 \& }}
533 .Ve
534 .PP
535 This is caused by the fact that a block by itself acts as a loop that
536 executes once, see "Basic BLOCKs".
537 .PP
538 The form \f(CW\*(C`while/if BLOCK BLOCK\*(C'\fR, available in Perl 4, is no longer
539 available. Replace any occurrence of \f(CW\*(C`if BLOCK\*(C'\fR by \f(CW\*(C`if (do BLOCK)\*(C'\fR.
540 .SS "For Loops"
541 .IX Xref "for foreach"
542 .IX Subsection "For Loops"
543 Perl's C\-style \f(CW\*(C`for\*(C'\fR loop works like the corresponding \f(CW\*(C`while\*(C'\fR loop;
544 that means that this:
545 .PP
546 .Vb 3
547 \& for ($i = 1; $i < 10; $i++) {
548 \& ...
549 \& }
550 .Ve
551 .PP
552 is the same as this:
553 .PP
554 .Vb 6
555 \& $i = 1;
556 \& while ($i < 10) {
557 \& ...
558 \& } continue {
559 \& $i++;
560 \& }
561 .Ve
562 .PP
563 There is one minor difference: if variables are declared with \f(CW\*(C`my\*(C'\fR
564 in the initialization section of the \f(CW\*(C`for\*(C'\fR, the lexical scope of
565 those variables is exactly the \f(CW\*(C`for\*(C'\fR loop (the body of the loop
566 and the control sections). To illustrate:
567 .IX Xref "my"
568 .PP
569 .Vb 5
570 \& my $i = \*(Aqsamba\*(Aq;
571 \& for (my $i = 1; $i <= 4; $i++) {
572 \& print "$i\en";
573 \& }
574 \& print "$i\en";
575 .Ve
576 .PP
577 when executed, gives:
578 .PP
579 .Vb 5
580 \& 1
581 \& 2
582 \& 3
583 \& 4
584 \& samba
585 .Ve
586 .PP
587 As a special case, if the test in the \f(CW\*(C`for\*(C'\fR loop (or the corresponding
588 \&\f(CW\*(C`while\*(C'\fR loop) is empty, it is treated as true. That is, both
589 .PP
590 .Vb 3
591 \& for (;;) {
592 \& ...
593 \& }
594 .Ve
595 .PP
596 and
597 .PP
598 .Vb 3
599 \& while () {
600 \& ...
601 \& }
602 .Ve
603 .PP
604 are treated as infinite loops.
605 .PP
606 Besides the normal array index looping, \f(CW\*(C`for\*(C'\fR can lend itself
607 to many other interesting applications. Here's one that avoids the
608 problem you get into if you explicitly test for end-of-file on
609 an interactive file descriptor causing your program to appear to
610 hang.
611 .IX Xref "eof end-of-file end of file"
612 .PP
613 .Vb 5
614 \& $on_a_tty = \-t STDIN && \-t STDOUT;
615 \& sub prompt { print "yes? " if $on_a_tty }
616 \& for ( prompt(); <STDIN>; prompt() ) {
617 \& # do something
618 \& }
619 .Ve
620 .PP
621 The condition expression of a \f(CW\*(C`for\*(C'\fR loop gets the same magic treatment of
622 \&\f(CW\*(C`readline\*(C'\fR et al that the condition expression of a \f(CW\*(C`while\*(C'\fR loop gets.
623 .SS "Foreach Loops"
624 .IX Xref "for foreach"
625 .IX Subsection "Foreach Loops"
626 The \f(CW\*(C`foreach\*(C'\fR loop iterates over a normal list value and sets the scalar
627 variable VAR to be each element of the list in turn. If the variable
628 is preceded with the keyword \f(CW\*(C`my\*(C'\fR, then it is lexically scoped, and
629 is therefore visible only within the loop. Otherwise, the variable is
630 implicitly local to the loop and regains its former value upon exiting
631 the loop. If the variable was previously declared with \f(CW\*(C`my\*(C'\fR, it uses
632 that variable instead of the global one, but it's still localized to
633 the loop. This implicit localization occurs \fIonly\fR for non C\-style
634 loops.
635 .IX Xref "my local"
636 .PP
637 The \f(CW\*(C`foreach\*(C'\fR keyword is actually a synonym for the \f(CW\*(C`for\*(C'\fR keyword, so
638 you can use either. If VAR is omitted, \f(CW$_\fR is set to each value.
639 .IX Xref "$_"
640 .PP
641 If any element of LIST is an lvalue, you can modify it by modifying
642 VAR inside the loop. Conversely, if any element of LIST is NOT an
643 lvalue, any attempt to modify that element will fail. In other words,
644 the \f(CW\*(C`foreach\*(C'\fR loop index variable is an implicit alias for each item
645 in the list that you're looping over.
646 .IX Xref "alias"
647 .PP
648 If any part of LIST is an array, \f(CW\*(C`foreach\*(C'\fR will get very confused if
649 you add or remove elements within the loop body, for example with
650 \&\f(CW\*(C`splice\*(C'\fR. So don't do that.
651 .IX Xref "splice"
652 .PP
653 \&\f(CW\*(C`foreach\*(C'\fR probably won't do what you expect if VAR is a tied or other
654 special variable. Don't do that either.
655 .PP
656 As of Perl 5.22, there is an experimental variant of this loop that accepts
657 a variable preceded by a backslash for VAR, in which case the items in the
658 LIST must be references. The backslashed variable will become an alias
659 to each referenced item in the LIST, which must be of the correct type.
660 The variable needn't be a scalar in this case, and the backslash may be
661 followed by \f(CW\*(C`my\*(C'\fR. To use this form, you must enable the \f(CW\*(C`refaliasing\*(C'\fR
662 feature via \f(CW\*(C`use feature\*(C'\fR. (See feature. See also "Assigning
663 to References" in perlref.)
664 .PP
665 As of Perl 5.36, you can iterate over multiple values at a time.
666 You can only iterate with lexical scalars as the iterator variables \- unlike
667 list assignment, it's not possible to use \f(CW\*(C`undef\*(C'\fR to signify a value that
668 isn't wanted. This is a limitation of the current implementation, and might
669 be changed in the future.
670 .PP
671 If the size of the LIST is not an exact multiple of the number of iterator
672 variables, then on the last iteration the "excess" iterator variables are
673 aliases to \f(CW\*(C`undef\*(C'\fR, as if the LIST had \f(CW\*(C`, undef\*(C'\fR appended as many times as
674 needed for its length to become an exact multiple. This happens whether
675 LIST is a literal LIST or an array \- ie arrays are not extended if their
676 size is not a multiple of the iteration size, consistent with iterating an
677 array one-at-a-time. As these padding elements are not lvalues, attempting
678 to modify them will fail, consistent with the behaviour when iterating a
679 list with literal \f(CW\*(C`undef\*(C'\fRs. If this is not the behaviour you desire, then
680 before the loop starts either explicitly extend your array to be an exact
681 multiple, or explicitly throw an exception.
682 .PP
683 Examples:
684 .PP
685 .Vb 1
686 \& for (@ary) { s/foo/bar/ }
687 \&
688 \& for my $elem (@elements) {
689 \& $elem *= 2;
690 \& }
691 \&
692 \& for $count (reverse(1..10), "BOOM") {
693 \& print $count, "\en";
694 \& sleep(1);
695 \& }
696 \&
697 \& for (1..15) { print "Merry Christmas\en"; }
698 \&
699 \& foreach $item (split(/:[\e\e\en:]*/, $ENV{TERMCAP})) {
700 \& print "Item: $item\en";
701 \& }
702 \&
703 \& use feature "refaliasing";
704 \& no warnings "experimental::refaliasing";
705 \& foreach \emy %hash (@array_of_hash_references) {
706 \& # do something with each %hash
707 \& }
708 \&
709 \& foreach my ($foo, $bar, $baz) (@list) {
710 \& # do something three\-at\-a\-time
711 \& }
712 \&
713 \& foreach my ($key, $value) (%hash) {
714 \& # iterate over the hash
715 \& # The hash is immediately copied to a flat list before the loop
716 \& # starts. The list contains copies of keys but aliases of values.
717 \& # This is the same behaviour as for $var (%hash) {...}
718 \& }
719 .Ve
720 .PP
721 Here's how a C programmer might code up a particular algorithm in Perl:
722 .PP
723 .Vb 9
724 \& for (my $i = 0; $i < @ary1; $i++) {
725 \& for (my $j = 0; $j < @ary2; $j++) {
726 \& if ($ary1[$i] > $ary2[$j]) {
727 \& last; # can\*(Aqt go to outer :\-(
728 \& }
729 \& $ary1[$i] += $ary2[$j];
730 \& }
731 \& # this is where that last takes me
732 \& }
733 .Ve
734 .PP
735 Whereas here's how a Perl programmer more comfortable with the idiom might
736 do it:
737 .PP
738 .Vb 6
739 \& OUTER: for my $wid (@ary1) {
740 \& INNER: for my $jet (@ary2) {
741 \& next OUTER if $wid > $jet;
742 \& $wid += $jet;
743 \& }
744 \& }
745 .Ve
746 .PP
747 See how much easier this is? It's cleaner, safer, and faster. It's
748 cleaner because it's less noisy. It's safer because if code gets added
749 between the inner and outer loops later on, the new code won't be
750 accidentally executed. The \f(CW\*(C`next\*(C'\fR explicitly iterates the other loop
751 rather than merely terminating the inner one. And it's faster because
752 Perl executes a \f(CW\*(C`foreach\*(C'\fR statement more rapidly than it would the
753 equivalent C\-style \f(CW\*(C`for\*(C'\fR loop.
754 .PP
755 Perceptive Perl hackers may have noticed that a \f(CW\*(C`for\*(C'\fR loop has a return
756 value, and that this value can be captured by wrapping the loop in a \f(CW\*(C`do\*(C'\fR
757 block. The reward for this discovery is this cautionary advice: The
758 return value of a \f(CW\*(C`for\*(C'\fR loop is unspecified and may change without notice.
759 Do not rely on it.
760 .SS "Try Catch Exception Handling"
761 .IX Xref "try catch finally"
762 .IX Subsection "Try Catch Exception Handling"
763 The \f(CW\*(C`try\*(C'\fR/\f(CW\*(C`catch\*(C'\fR syntax provides control flow relating to exception
764 handling. The \f(CW\*(C`try\*(C'\fR keyword introduces a block which will be executed when it
765 is encountered, and the \f(CW\*(C`catch\*(C'\fR block provides code to handle any exception
766 that may be thrown by the first.
767 .PP
768 This syntax must first be enabled with \f(CW\*(C`use feature \*(Aqtry\*(Aq\*(C'\fR.
769 .PP
770 .Vb 1
771 \& use feature \*(Aqtry\*(Aq;
772 \&
773 \& try {
774 \& my $x = call_a_function();
775 \& $x < 100 or die "Too big";
776 \& send_output($x);
777 \& }
778 \& catch ($e) {
779 \& warn "Unable to output a value; $e";
780 \& }
781 \& print "Finished\en";
782 .Ve
783 .PP
784 Here, the body of the \f(CW\*(C`catch\*(C'\fR block (i.e. the \f(CW\*(C`warn\*(C'\fR statement) will be
785 executed if the initial block invokes the conditional \f(CW\*(C`die\*(C'\fR, or if either of
786 the functions it invokes throws an uncaught exception. The \f(CW\*(C`catch\*(C'\fR block can
787 inspect the \f(CW$e\fR lexical variable in this case to see what the exception was.
788 If no exception was thrown then the \f(CW\*(C`catch\*(C'\fR block does not happen. In either
789 case, execution will then continue from the following statement \- in this
790 example the \f(CW\*(C`print\*(C'\fR.
791 .PP
792 The \f(CW\*(C`catch\*(C'\fR keyword must be immediately followed by a variable declaration in
793 parentheses, which introduces a new variable visible to the body of the
794 subsequent block. Inside the block this variable will contain the exception
795 value that was thrown by the code in the \f(CW\*(C`try\*(C'\fR block. It is not necessary
796 to use the \f(CW\*(C`my\*(C'\fR keyword to declare this variable; this is implied (similar
797 as it is for subroutine signatures).
798 .PP
799 Both the \f(CW\*(C`try\*(C'\fR and the \f(CW\*(C`catch\*(C'\fR blocks are permitted to contain control-flow
800 expressions, such as \f(CW\*(C`return\*(C'\fR, \f(CW\*(C`goto\*(C'\fR, or \f(CW\*(C`next\*(C'\fR/\f(CW\*(C`last\*(C'\fR/\f(CW\*(C`redo\*(C'\fR. In all
801 cases they behave as expected without warnings. In particular, a \f(CW\*(C`return\*(C'\fR
802 expression inside the \f(CW\*(C`try\*(C'\fR block will make its entire containing function
803 return \- this is in contrast to its behaviour inside an \f(CW\*(C`eval\*(C'\fR block, where
804 it would only make that block return.
805 .PP
806 Like other control-flow syntax, \f(CW\*(C`try\*(C'\fR and \f(CW\*(C`catch\*(C'\fR will yield the last
807 evaluated value when placed as the final statement in a function or a \f(CW\*(C`do\*(C'\fR
808 block. This permits the syntax to be used to create a value. In this case
809 remember not to use the \f(CW\*(C`return\*(C'\fR expression, or that will cause the
810 containing function to return.
811 .PP
812 .Vb 9
813 \& my $value = do {
814 \& try {
815 \& get_thing(@args);
816 \& }
817 \& catch ($e) {
818 \& warn "Unable to get thing \- $e";
819 \& $DEFAULT_THING;
820 \& }
821 \& };
822 .Ve
823 .PP
824 As with other control-flow syntax, \f(CW\*(C`try\*(C'\fR blocks are not visible to
825 \&\f(CWcaller()\fR (just as for example, \f(CW\*(C`while\*(C'\fR or \f(CW\*(C`foreach\*(C'\fR loops are not).
826 Successive levels of the \f(CW\*(C`caller\*(C'\fR result can see subroutine calls and
827 \&\f(CW\*(C`eval\*(C'\fR blocks, because those affect the way that \f(CW\*(C`return\*(C'\fR would work. Since
828 \&\f(CW\*(C`try\*(C'\fR blocks do not intercept \f(CW\*(C`return\*(C'\fR, they are not of interest to
829 \&\f(CW\*(C`caller\*(C'\fR.
830 .PP
831 The \f(CW\*(C`try\*(C'\fR and \f(CW\*(C`catch\*(C'\fR blocks may optionally be followed by a third block
832 introduced by the \f(CW\*(C`finally\*(C'\fR keyword. This third block is executed after the
833 rest of the construct has finished.
834 .PP
835 .Vb 9
836 \& try {
837 \& call_a_function();
838 \& }
839 \& catch ($e) {
840 \& warn "Unable to call; $e";
841 \& }
842 \& finally {
843 \& print "Finished\en";
844 \& }
845 .Ve
846 .PP
847 The \f(CW\*(C`finally\*(C'\fR block is equivalent to using a \f(CW\*(C`defer\*(C'\fR block and will be
848 invoked in the same situations; whether the \f(CW\*(C`try\*(C'\fR block completes
849 successfully, throws an exception, or transfers control elsewhere by using
850 \&\f(CW\*(C`return\*(C'\fR, a loop control, or \f(CW\*(C`goto\*(C'\fR.
851 .PP
852 Unlike the \f(CW\*(C`try\*(C'\fR and \f(CW\*(C`catch\*(C'\fR blocks, a \f(CW\*(C`finally\*(C'\fR block is not permitted to
853 \&\f(CW\*(C`return\*(C'\fR, \f(CW\*(C`goto\*(C'\fR or use any loop controls. The final expression value is
854 ignored, and does not affect the return value of the containing function even
855 if it is placed last in the function.
856 .PP
857 Use of this \f(CW\*(C`finally\*(C'\fR block syntax is currently experimental and will emit a
858 warning in the \f(CW\*(C`experimental::try\*(C'\fR category.
859 .SS "Basic BLOCKs"
860 .IX Xref "block"
861 .IX Subsection "Basic BLOCKs"
862 A BLOCK by itself (labeled or not) is semantically equivalent to a
863 loop that executes once. Thus you can use any of the loop control
864 statements in it to leave or restart the block. (Note that this is
865 \&\fINOT\fR true in \f(CW\*(C`eval{}\*(C'\fR, \f(CW\*(C`sub{}\*(C'\fR, or contrary to popular belief
866 \&\f(CW\*(C`do{}\*(C'\fR blocks, which do \fINOT\fR count as loops.) The \f(CW\*(C`continue\*(C'\fR
867 block is optional.
868 .PP
869 The BLOCK construct can be used to emulate case structures.
870 .PP
871 .Vb 6
872 \& SWITCH: {
873 \& if (/^abc/) { $abc = 1; last SWITCH; }
874 \& if (/^def/) { $def = 1; last SWITCH; }
875 \& if (/^xyz/) { $xyz = 1; last SWITCH; }
876 \& $nothing = 1;
877 \& }
878 .Ve
879 .PP
880 You'll also find that \f(CW\*(C`foreach\*(C'\fR loop used to create a topicalizer
881 and a switch:
882 .PP
883 .Vb 7
884 \& SWITCH:
885 \& for ($var) {
886 \& if (/^abc/) { $abc = 1; last SWITCH; }
887 \& if (/^def/) { $def = 1; last SWITCH; }
888 \& if (/^xyz/) { $xyz = 1; last SWITCH; }
889 \& $nothing = 1;
890 \& }
891 .Ve
892 .PP
893 Such constructs are quite frequently used, both because older versions of
894 Perl had no official \f(CW\*(C`switch\*(C'\fR statement, and also because the new version
895 described immediately below remains experimental and can sometimes be confusing.
896 .SS "defer blocks"
897 .IX Xref "defer"
898 .IX Subsection "defer blocks"
899 A block prefixed by the \f(CW\*(C`defer\*(C'\fR modifier provides a section of code which
900 runs at a later time during scope exit.
901 .PP
902 A \f(CW\*(C`defer\*(C'\fR block can appear at any point where a regular block or other
903 statement is permitted. If the flow of execution reaches this statement, the
904 body of the block is stored for later, but not invoked immediately. When the
905 flow of control leaves the containing block for any reason, this stored block
906 is executed on the way past. It provides a means of deferring execution until
907 a later time. This acts similarly to syntax provided by some other languages,
908 often using keywords named \f(CW\*(C`try / finally\*(C'\fR.
909 .PP
910 This syntax is available since Perl 5.36 if enabled by the \f(CW\*(C`defer\*(C'\fR named feature,
911 and is currently experimental. If experimental warnings are enabled it will emit a
912 warning when used.
913 .PP
914 .Vb 1
915 \& use feature \*(Aqdefer\*(Aq;
916 \&
917 \& {
918 \& say "This happens first";
919 \& defer { say "This happens last"; }
920 \&
921 \& say "And this happens inbetween";
922 \& }
923 .Ve
924 .PP
925 If multiple \f(CW\*(C`defer\*(C'\fR blocks are contained in a single scope, they are
926 executed in LIFO order; the last one reached is the first one executed.
927 .PP
928 The code stored by the \f(CW\*(C`defer\*(C'\fR block will be invoked when control leaves
929 its containing block due to regular fallthrough, explicit \f(CW\*(C`return\*(C'\fR,
930 exceptions thrown by \f(CW\*(C`die\*(C'\fR or propagated by functions called by it, \f(CW\*(C`goto\*(C'\fR,
931 or any of the loop control statements \f(CW\*(C`next\*(C'\fR, \f(CW\*(C`last\*(C'\fR or \f(CW\*(C`redo\*(C'\fR.
932 .PP
933 If the flow of control does not reach the \f(CW\*(C`defer\*(C'\fR statement itself then its
934 body is not stored for later execution. (This is in direct contrast to the
935 code provided by an \f(CW\*(C`END\*(C'\fR phaser block, which is always enqueued by the
936 compiler, regardless of whether execution ever reached the line it was given
937 on.)
938 .PP
939 .Vb 1
940 \& use feature \*(Aqdefer\*(Aq;
941 \&
942 \& {
943 \& defer { say "This will run"; }
944 \& return;
945 \& defer { say "This will not"; }
946 \& }
947 .Ve
948 .PP
949 Exceptions thrown by code inside a \f(CW\*(C`defer\*(C'\fR block will propagate to the
950 caller in the same way as any other exception thrown by normal code.
951 .PP
952 If the \f(CW\*(C`defer\*(C'\fR block is being executed due to a thrown exception and throws
953 another one it is not specified what happens, beyond that the caller will
954 definitely receive an exception.
955 .PP
956 Besides throwing an exception, a \f(CW\*(C`defer\*(C'\fR block is not permitted to
957 otherwise alter the control flow of its surrounding code. In particular, it
958 may not cause its containing function to \f(CW\*(C`return\*(C'\fR, nor may it \f(CW\*(C`goto\*(C'\fR a
959 label, or control a containing loop using \f(CW\*(C`next\*(C'\fR, \f(CW\*(C`last\*(C'\fR or \f(CW\*(C`redo\*(C'\fR. These
960 constructions are however, permitted entirely within the body of the
961 \&\f(CW\*(C`defer\*(C'\fR.
962 .PP
963 .Vb 1
964 \& use feature \*(Aqdefer\*(Aq;
965 \&
966 \& {
967 \& defer {
968 \& foreach ( 1 .. 5 ) {
969 \& last if $_ == 3; # this is permitted
970 \& }
971 \& }
972 \& }
973 \&
974 \& {
975 \& foreach ( 6 .. 10 ) {
976 \& defer {
977 \& last if $_ == 8; # this is not
978 \& }
979 \& }
980 \& }
981 .Ve
982 .SS "Switch Statements"
983 .IX Subsection "Switch Statements"
984
985 .IX Xref "switch case given when default"
986 .PP
987 Starting from Perl 5.10.1 (well, 5.10.0, but it didn't work
988 right), you can say
989 .PP
990 .Vb 1
991 \& use feature "switch";
992 .Ve
993 .PP
994 to enable an experimental switch feature. This is loosely based on an
995 old version of a Raku proposal, but it no longer resembles the Raku
996 construct. You also get the switch feature whenever you declare that your
997 code prefers to run under a version of Perl between 5.10 and 5.34. For
998 example:
999 .PP
1000 .Vb 1
1001 \& use v5.14;
1002 .Ve
1003 .PP
1004 Under the "switch" feature, Perl gains the experimental keywords
1005 \&\f(CW\*(C`given\*(C'\fR, \f(CW\*(C`when\*(C'\fR, \f(CW\*(C`default\*(C'\fR, \f(CW\*(C`continue\*(C'\fR, and \f(CW\*(C`break\*(C'\fR.
1006 Starting from Perl 5.16, one can prefix the switch
1007 keywords with \f(CW\*(C`CORE::\*(C'\fR to access the feature without a \f(CW\*(C`use feature\*(C'\fR
1008 statement. The keywords \f(CW\*(C`given\*(C'\fR and
1009 \&\f(CW\*(C`when\*(C'\fR are analogous to \f(CW\*(C`switch\*(C'\fR and
1010 \&\f(CW\*(C`case\*(C'\fR in other languages \-\- though \f(CW\*(C`continue\*(C'\fR is not \-\- so the code
1011 in the previous section could be rewritten as
1012 .PP
1013 .Vb 7
1014 \& use v5.10.1;
1015 \& for ($var) {
1016 \& when (/^abc/) { $abc = 1 }
1017 \& when (/^def/) { $def = 1 }
1018 \& when (/^xyz/) { $xyz = 1 }
1019 \& default { $nothing = 1 }
1020 \& }
1021 .Ve
1022 .PP
1023 The \f(CW\*(C`foreach\*(C'\fR is the non-experimental way to set a topicalizer.
1024 If you wish to use the highly experimental \f(CW\*(C`given\*(C'\fR, that could be
1025 written like this:
1026 .PP
1027 .Vb 7
1028 \& use v5.10.1;
1029 \& given ($var) {
1030 \& when (/^abc/) { $abc = 1 }
1031 \& when (/^def/) { $def = 1 }
1032 \& when (/^xyz/) { $xyz = 1 }
1033 \& default { $nothing = 1 }
1034 \& }
1035 .Ve
1036 .PP
1037 As of 5.14, that can also be written this way:
1038 .PP
1039 .Vb 7
1040 \& use v5.14;
1041 \& for ($var) {
1042 \& $abc = 1 when /^abc/;
1043 \& $def = 1 when /^def/;
1044 \& $xyz = 1 when /^xyz/;
1045 \& default { $nothing = 1 }
1046 \& }
1047 .Ve
1048 .PP
1049 Or if you don't care to play it safe, like this:
1050 .PP
1051 .Vb 7
1052 \& use v5.14;
1053 \& given ($var) {
1054 \& $abc = 1 when /^abc/;
1055 \& $def = 1 when /^def/;
1056 \& $xyz = 1 when /^xyz/;
1057 \& default { $nothing = 1 }
1058 \& }
1059 .Ve
1060 .PP
1061 The arguments to \f(CW\*(C`given\*(C'\fR and \f(CW\*(C`when\*(C'\fR are in scalar context,
1062 and \f(CW\*(C`given\*(C'\fR assigns the \f(CW$_\fR variable its topic value.
1063 .PP
1064 Exactly what the \fIEXPR\fR argument to \f(CW\*(C`when\*(C'\fR does is hard to describe
1065 precisely, but in general, it tries to guess what you want done. Sometimes
1066 it is interpreted as \f(CW\*(C`$_ ~~ \fR\f(CIEXPR\fR\f(CW\*(C'\fR, and sometimes it is not. It
1067 also behaves differently when lexically enclosed by a \f(CW\*(C`given\*(C'\fR block than
1068 it does when dynamically enclosed by a \f(CW\*(C`foreach\*(C'\fR loop. The rules are far
1069 too difficult to understand to be described here. See "Experimental Details
1070 on given and when" later on.
1071 .PP
1072 Due to an unfortunate bug in how \f(CW\*(C`given\*(C'\fR was implemented between Perl 5.10
1073 and 5.16, under those implementations the version of \f(CW$_\fR governed by
1074 \&\f(CW\*(C`given\*(C'\fR is merely a lexically scoped copy of the original, not a
1075 dynamically scoped alias to the original, as it would be if it were a
1076 \&\f(CW\*(C`foreach\*(C'\fR or under both the original and the current Raku language
1077 specification. This bug was fixed in Perl 5.18 (and lexicalized \f(CW$_\fR itself
1078 was removed in Perl 5.24).
1079 .PP
1080 If your code still needs to run on older versions,
1081 stick to \f(CW\*(C`foreach\*(C'\fR for your topicalizer and
1082 you will be less unhappy.
1083 .SS Goto
1084 .IX Xref "goto"
1085 .IX Subsection "Goto"
1086 Although not for the faint of heart, Perl does support a \f(CW\*(C`goto\*(C'\fR
1087 statement. There are three forms: \f(CW\*(C`goto\*(C'\fR\-LABEL, \f(CW\*(C`goto\*(C'\fR\-EXPR, and
1088 \&\f(CW\*(C`goto\*(C'\fR\-&NAME. A loop's LABEL is not actually a valid target for
1089 a \f(CW\*(C`goto\*(C'\fR; it's just the name of the loop.
1090 .PP
1091 The \f(CW\*(C`goto\*(C'\fR\-LABEL form finds the statement labeled with LABEL and resumes
1092 execution there. It may not be used to go into any construct that
1093 requires initialization, such as a subroutine or a \f(CW\*(C`foreach\*(C'\fR loop. It
1094 also can't be used to go into a construct that is optimized away. It
1095 can be used to go almost anywhere else within the dynamic scope,
1096 including out of subroutines, but it's usually better to use some other
1097 construct such as \f(CW\*(C`last\*(C'\fR or \f(CW\*(C`die\*(C'\fR. The author of Perl has never felt the
1098 need to use this form of \f(CW\*(C`goto\*(C'\fR (in Perl, that is\-\-C is another matter).
1099 .PP
1100 The \f(CW\*(C`goto\*(C'\fR\-EXPR form expects a label name, whose scope will be resolved
1101 dynamically. This allows for computed \f(CW\*(C`goto\*(C'\fRs per FORTRAN, but isn't
1102 necessarily recommended if you're optimizing for maintainability:
1103 .PP
1104 .Vb 1
1105 \& goto(("FOO", "BAR", "GLARCH")[$i]);
1106 .Ve
1107 .PP
1108 The \f(CW\*(C`goto\*(C'\fR\-&NAME form is highly magical, and substitutes a call to the
1109 named subroutine for the currently running subroutine. This is used by
1110 \&\f(CWAUTOLOAD()\fR subroutines that wish to load another subroutine and then
1111 pretend that the other subroutine had been called in the first place
1112 (except that any modifications to \f(CW@_\fR in the current subroutine are
1113 propagated to the other subroutine.) After the \f(CW\*(C`goto\*(C'\fR, not even \f(CWcaller()\fR
1114 will be able to tell that this routine was called first.
1115 .PP
1116 In almost all cases like this, it's usually a far, far better idea to use the
1117 structured control flow mechanisms of \f(CW\*(C`next\*(C'\fR, \f(CW\*(C`last\*(C'\fR, or \f(CW\*(C`redo\*(C'\fR instead of
1118 resorting to a \f(CW\*(C`goto\*(C'\fR. For certain applications, the catch and throw pair of
1119 \&\f(CW\*(C`eval{}\*(C'\fR and \fBdie()\fR for exception processing can also be a prudent approach.
1120 .SS "The Ellipsis Statement"
1121 .IX Xref "... ... statement ellipsis operator elliptical statement unimplemented statement unimplemented operator yada-yada yada-yada operator ... operator whatever operator triple-dot operator"
1122 .IX Subsection "The Ellipsis Statement"
1123 Beginning in Perl 5.12, Perl accepts an ellipsis, "\f(CW\*(C`...\*(C'\fR", as a
1124 placeholder for code that you haven't implemented yet.
1125 When Perl 5.12 or later encounters an ellipsis statement, it parses this
1126 without error, but if and when you should actually try to execute it, Perl
1127 throws an exception with the text \f(CW\*(C`Unimplemented\*(C'\fR:
1128 .PP
1129 .Vb 6
1130 \& use v5.12;
1131 \& sub unimplemented { ... }
1132 \& eval { unimplemented() };
1133 \& if ($@ =~ /^Unimplemented at /) {
1134 \& say "I found an ellipsis!";
1135 \& }
1136 .Ve
1137 .PP
1138 You can only use the elliptical statement to stand in for a complete
1139 statement. Syntactically, "\f(CW\*(C`...;\*(C'\fR" is a complete statement, but,
1140 as with other kinds of semicolon-terminated statement, the semicolon
1141 may be omitted if "\f(CW\*(C`...\*(C'\fR" appears immediately before a closing brace.
1142 These examples show how the ellipsis works:
1143 .PP
1144 .Vb 10
1145 \& use v5.12;
1146 \& { ... }
1147 \& sub foo { ... }
1148 \& ...;
1149 \& eval { ... };
1150 \& sub somemeth {
1151 \& my $self = shift;
1152 \& ...;
1153 \& }
1154 \& $x = do {
1155 \& my $n;
1156 \& ...;
1157 \& say "Hurrah!";
1158 \& $n;
1159 \& };
1160 .Ve
1161 .PP
1162 The elliptical statement cannot stand in for an expression that
1163 is part of a larger statement.
1164 These examples of attempts to use an ellipsis are syntax errors:
1165 .PP
1166 .Vb 1
1167 \& use v5.12;
1168 \&
1169 \& print ...;
1170 \& open(my $fh, ">", "/dev/passwd") or ...;
1171 \& if ($condition && ... ) { say "Howdy" };
1172 \& ... if $x > $y;
1173 \& say "Cromulent" if ...;
1174 \& $flub = 5 + ...;
1175 .Ve
1176 .PP
1177 There are some cases where Perl can't immediately tell the difference
1178 between an expression and a statement. For instance, the syntax for a
1179 block and an anonymous hash reference constructor look the same unless
1180 there's something in the braces to give Perl a hint. The ellipsis is a
1181 syntax error if Perl doesn't guess that the \f(CW\*(C`{ ... }\*(C'\fR is a block.
1182 Inside your block, you can use a \f(CW\*(C`;\*(C'\fR before the ellipsis to denote that the
1183 \&\f(CW\*(C`{ ... }\*(C'\fR is a block and not a hash reference constructor.
1184 .PP
1185 Note: Some folks colloquially refer to this bit of punctuation as a
1186 "yada-yada" or "triple-dot", but its true name
1187 is actually an ellipsis.
1188 .SS "PODs: Embedded Documentation"
1189 .IX Xref "POD documentation"
1190 .IX Subsection "PODs: Embedded Documentation"
1191 Perl has a mechanism for intermixing documentation with source code.
1192 While it's expecting the beginning of a new statement, if the compiler
1193 encounters a line that begins with an equal sign and a word, like this
1194 .PP
1195 .Vb 1
1196 \& =head1 Here There Be Pods!
1197 .Ve
1198 .PP
1199 Then that text and all remaining text up through and including a line
1200 beginning with \f(CW\*(C`=cut\*(C'\fR will be ignored. The format of the intervening
1201 text is described in perlpod.
1202 .PP
1203 This allows you to intermix your source code
1204 and your documentation text freely, as in
1205 .PP
1206 .Vb 1
1207 \& =item snazzle($)
1208 \&
1209 \& The snazzle() function will behave in the most spectacular
1210 \& form that you can possibly imagine, not even excepting
1211 \& cybernetic pyrotechnics.
1212 \&
1213 \& =cut back to the compiler, nuff of this pod stuff!
1214 \&
1215 \& sub snazzle($) {
1216 \& my $thingie = shift;
1217 \& .........
1218 \& }
1219 .Ve
1220 .PP
1221 Note that pod translators should look at only paragraphs beginning
1222 with a pod directive (it makes parsing easier), whereas the compiler
1223 actually knows to look for pod escapes even in the middle of a
1224 paragraph. This means that the following secret stuff will be
1225 ignored by both the compiler and the translators.
1226 .PP
1227 .Vb 5
1228 \& $x=3;
1229 \& =secret stuff
1230 \& warn "Neither POD nor CODE!?"
1231 \& =cut back
1232 \& print "got $x\en";
1233 .Ve
1234 .PP
1235 You probably shouldn't rely upon the \f(CWwarn()\fR being podded out forever.
1236 Not all pod translators are well-behaved in this regard, and perhaps
1237 the compiler will become pickier.
1238 .PP
1239 One may also use pod directives to quickly comment out a section
1240 of code.
1241 .SS "Plain Old Comments (Not!)"
1242 .IX Xref "comment line # preprocessor eval"
1243 .IX Subsection "Plain Old Comments (Not!)"
1244 Perl can process line directives, much like the C preprocessor. Using
1245 this, one can control Perl's idea of filenames and line numbers in
1246 error or warning messages (especially for strings that are processed
1247 with \f(CWeval()\fR). The syntax for this mechanism is almost the same as for
1248 most C preprocessors: it matches the regular expression
1249 .PP
1250 .Vb 5
1251 \& # example: \*(Aq# line 42 "new_filename.plx"\*(Aq
1252 \& /^\e# \es*
1253 \& line \es+ (\ed+) \es*
1254 \& (?:\es("?)([^"]+)\eg2)? \es*
1255 \& $/x
1256 .Ve
1257 .PP
1258 with \f(CW$1\fR being the line number for the next line, and \f(CW$3\fR being
1259 the optional filename (specified with or without quotes). Note that
1260 no whitespace may precede the \f(CW\*(C`#\*(C'\fR, unlike modern C preprocessors.
1261 .PP
1262 There is a fairly obvious gotcha included with the line directive:
1263 Debuggers and profilers will only show the last source line to appear
1264 at a particular line number in a given file. Care should be taken not
1265 to cause line number collisions in code you'd like to debug later.
1266 .PP
1267 Here are some examples that you should be able to type into your command
1268 shell:
1269 .PP
1270 .Vb 6
1271 \& % perl
1272 \& # line 200 "bzzzt"
1273 \& # the \*(Aq#\*(Aq on the previous line must be the first char on line
1274 \& die \*(Aqfoo\*(Aq;
1275 \& _\|_END_\|_
1276 \& foo at bzzzt line 201.
1277 \&
1278 \& % perl
1279 \& # line 200 "bzzzt"
1280 \& eval qq[\en#line 2001 ""\endie \*(Aqfoo\*(Aq]; print $@;
1281 \& _\|_END_\|_
1282 \& foo at \- line 2001.
1283 \&
1284 \& % perl
1285 \& eval qq[\en#line 200 "foo bar"\endie \*(Aqfoo\*(Aq]; print $@;
1286 \& _\|_END_\|_
1287 \& foo at foo bar line 200.
1288 \&
1289 \& % perl
1290 \& # line 345 "goop"
1291 \& eval "\en#line " . _\|_LINE_\|_ . \*(Aq "\*(Aq . _\|_FILE_\|_ ."\e"\endie \*(Aqfoo\*(Aq";
1292 \& print $@;
1293 \& _\|_END_\|_
1294 \& foo at goop line 345.
1295 .Ve
1296 .SS "Experimental Details on given and when"
1297 .IX Subsection "Experimental Details on given and when"
1298 As previously mentioned, the "switch" feature is considered highly
1299 experimental (it is also scheduled to be removed in perl 5.42.0);
1300 it is subject to change with little notice. In particular,
1301 \&\f(CW\*(C`when\*(C'\fR has tricky behaviours that are expected to change to become less
1302 tricky in the future. Do not rely upon its current (mis)implementation.
1303 Before Perl 5.18, \f(CW\*(C`given\*(C'\fR also had tricky behaviours that you should still
1304 beware of if your code must run on older versions of Perl.
1305 .PP
1306 Here is a longer example of \f(CW\*(C`given\*(C'\fR:
1307 .PP
1308 .Vb 10
1309 \& use feature ":5.10";
1310 \& given ($foo) {
1311 \& when (undef) {
1312 \& say \*(Aq$foo is undefined\*(Aq;
1313 \& }
1314 \& when ("foo") {
1315 \& say \*(Aq$foo is the string "foo"\*(Aq;
1316 \& }
1317 \& when ([1,3,5,7,9]) {
1318 \& say \*(Aq$foo is an odd digit\*(Aq;
1319 \& continue; # Fall through
1320 \& }
1321 \& when ($_ < 100) {
1322 \& say \*(Aq$foo is numerically less than 100\*(Aq;
1323 \& }
1324 \& when (\e&complicated_check) {
1325 \& say \*(Aqa complicated check for $foo is true\*(Aq;
1326 \& }
1327 \& default {
1328 \& die q(I don\*(Aqt know what to do with $foo);
1329 \& }
1330 \& }
1331 .Ve
1332 .PP
1333 Before Perl 5.18, \f(CWgiven(EXPR)\fR assigned the value of \fIEXPR\fR to
1334 merely a lexically scoped \fR\f(BIcopy\fR\fI\fR (!) of \f(CW$_\fR, not a dynamically
1335 scoped alias the way \f(CW\*(C`foreach\*(C'\fR does. That made it similar to
1336 .PP
1337 .Vb 1
1338 \& do { my $_ = EXPR; ... }
1339 .Ve
1340 .PP
1341 except that the block was automatically broken out of by a successful
1342 \&\f(CW\*(C`when\*(C'\fR or an explicit \f(CW\*(C`break\*(C'\fR. Because it was only a copy, and because
1343 it was only lexically scoped, not dynamically scoped, you could not do the
1344 things with it that you are used to in a \f(CW\*(C`foreach\*(C'\fR loop. In particular,
1345 it did not work for arbitrary function calls if those functions might try
1346 to access \f(CW$_\fR. Best stick to \f(CW\*(C`foreach\*(C'\fR for that.
1347 .PP
1348 Most of the power comes from the implicit smartmatching that can
1349 sometimes apply. Most of the time, \f(CWwhen(EXPR)\fR is treated as an
1350 implicit smartmatch of \f(CW$_\fR, that is, \f(CW\*(C`$_ ~~ EXPR\*(C'\fR. (See
1351 "Smartmatch Operator" in perlop for more information on smartmatching.)
1352 But when \fIEXPR\fR is one of the 10 exceptional cases (or things like them)
1353 listed below, it is used directly as a boolean.
1354 .IP 1. 4
1355 .IX Item "1."
1356 A user-defined subroutine call or a method invocation.
1357 .IP 2. 4
1358 .IX Item "2."
1359 A regular expression match in the form of \f(CW\*(C`/REGEX/\*(C'\fR, \f(CW\*(C`$foo =~ /REGEX/\*(C'\fR,
1360 or \f(CW\*(C`$foo =~ EXPR\*(C'\fR. Also, a negated regular expression match in
1361 the form \f(CW\*(C`!/REGEX/\*(C'\fR, \f(CW\*(C`$foo !~ /REGEX/\*(C'\fR, or \f(CW\*(C`$foo !~ EXPR\*(C'\fR.
1362 .IP 3. 4
1363 .IX Item "3."
1364 A smart match that uses an explicit \f(CW\*(C`~~\*(C'\fR operator, such as \f(CW\*(C`EXPR ~~ EXPR\*(C'\fR.
1365 .Sp
1366 \&\fBNOTE:\fR You will often have to use \f(CW\*(C`$c ~~ $_\*(C'\fR because the default case
1367 uses \f(CW\*(C`$_ ~~ $c\*(C'\fR , which is frequently the opposite of what you want.
1368 .IP 4. 4
1369 .IX Item "4."
1370 A boolean comparison operator such as \f(CW\*(C`$_ < 10\*(C'\fR or \f(CW\*(C`$x eq "abc"\*(C'\fR. The
1371 relational operators that this applies to are the six numeric comparisons
1372 (\f(CW\*(C`<\*(C'\fR, \f(CW\*(C`>\*(C'\fR, \f(CW\*(C`<=\*(C'\fR, \f(CW\*(C`>=\*(C'\fR, \f(CW\*(C`==\*(C'\fR, and \f(CW\*(C`!=\*(C'\fR), and
1373 the six string comparisons (\f(CW\*(C`lt\*(C'\fR, \f(CW\*(C`gt\*(C'\fR, \f(CW\*(C`le\*(C'\fR, \f(CW\*(C`ge\*(C'\fR, \f(CW\*(C`eq\*(C'\fR, and \f(CW\*(C`ne\*(C'\fR).
1374 .IP 5. 4
1375 .IX Item "5."
1376 At least the three builtin functions \f(CWdefined(...)\fR, \f(CWexists(...)\fR, and
1377 \&\f(CWeof(...)\fR. We might someday add more of these later if we think of them.
1378 .IP 6. 4
1379 .IX Item "6."
1380 A negated expression, whether \f(CW\*(C`!(EXPR)\*(C'\fR or \f(CWnot(EXPR)\fR, or a logical
1381 exclusive-or, \f(CW\*(C`(EXPR1) xor (EXPR2)\*(C'\fR. The bitwise versions (\f(CW\*(C`~\*(C'\fR and \f(CW\*(C`^\*(C'\fR)
1382 are not included.
1383 .IP 7. 4
1384 .IX Item "7."
1385 A filetest operator, with exactly 4 exceptions: \f(CW\*(C`\-s\*(C'\fR, \f(CW\*(C`\-M\*(C'\fR, \f(CW\*(C`\-A\*(C'\fR, and
1386 \&\f(CW\*(C`\-C\*(C'\fR, as these return numerical values, not boolean ones. The \f(CW\*(C`\-z\*(C'\fR
1387 filetest operator is not included in the exception list.
1388 .IP 8. 4
1389 .IX Item "8."
1390 The \f(CW\*(C`..\*(C'\fR and \f(CW\*(C`...\*(C'\fR flip-flop operators. Note that the \f(CW\*(C`...\*(C'\fR flip-flop
1391 operator is completely different from the \f(CW\*(C`...\*(C'\fR elliptical statement
1392 just described.
1393 .PP
1394 In those 8 cases above, the value of EXPR is used directly as a boolean, so
1395 no smartmatching is done. You may think of \f(CW\*(C`when\*(C'\fR as a smartsmartmatch.
1396 .PP
1397 Furthermore, Perl inspects the operands of logical operators to
1398 decide whether to use smartmatching for each one by applying the
1399 above test to the operands:
1400 .IP 9. 4
1401 .IX Item "9."
1402 If EXPR is \f(CW\*(C`EXPR1 && EXPR2\*(C'\fR or \f(CW\*(C`EXPR1 and EXPR2\*(C'\fR, the test is applied
1403 \&\fIrecursively\fR to both EXPR1 and EXPR2.
1404 Only if \fIboth\fR operands also pass the
1405 test, \fIrecursively\fR, will the expression be treated as boolean. Otherwise,
1406 smartmatching is used.
1407 .IP 10. 4
1408 .IX Item "10."
1409 If EXPR is \f(CW\*(C`EXPR1 || EXPR2\*(C'\fR, \f(CW\*(C`EXPR1 // EXPR2\*(C'\fR, or \f(CW\*(C`EXPR1 or EXPR2\*(C'\fR, the
1410 test is applied \fIrecursively\fR to EXPR1 only (which might itself be a
1411 higher-precedence AND operator, for example, and thus subject to the
1412 previous rule), not to EXPR2. If EXPR1 is to use smartmatching, then EXPR2
1413 also does so, no matter what EXPR2 contains. But if EXPR2 does not get to
1414 use smartmatching, then the second argument will not be either. This is
1415 quite different from the \f(CW\*(C`&&\*(C'\fR case just described, so be careful.
1416 .PP
1417 These rules are complicated, but the goal is for them to do what you want
1418 (even if you don't quite understand why they are doing it). For example:
1419 .PP
1420 .Vb 1
1421 \& when (/^\ed+$/ && $_ < 75) { ... }
1422 .Ve
1423 .PP
1424 will be treated as a boolean match because the rules say both
1425 a regex match and an explicit test on \f(CW$_\fR will be treated
1426 as boolean.
1427 .PP
1428 Also:
1429 .PP
1430 .Vb 1
1431 \& when ([qw(foo bar)] && /baz/) { ... }
1432 .Ve
1433 .PP
1434 will use smartmatching because only \fIone\fR of the operands is a boolean:
1435 the other uses smartmatching, and that wins.
1436 .PP
1437 Further:
1438 .PP
1439 .Vb 1
1440 \& when ([qw(foo bar)] || /^baz/) { ... }
1441 .Ve
1442 .PP
1443 will use smart matching (only the first operand is considered), whereas
1444 .PP
1445 .Vb 1
1446 \& when (/^baz/ || [qw(foo bar)]) { ... }
1447 .Ve
1448 .PP
1449 will test only the regex, which causes both operands to be
1450 treated as boolean. Watch out for this one, then, because an
1451 arrayref is always a true value, which makes it effectively
1452 redundant. Not a good idea.
1453 .PP
1454 Tautologous boolean operators are still going to be optimized
1455 away. Don't be tempted to write
1456 .PP
1457 .Vb 1
1458 \& when ("foo" or "bar") { ... }
1459 .Ve
1460 .PP
1461 This will optimize down to \f(CW"foo"\fR, so \f(CW"bar"\fR will never be considered (even
1462 though the rules say to use a smartmatch
1463 on \f(CW"foo"\fR). For an alternation like
1464 this, an array ref will work, because this will instigate smartmatching:
1465 .PP
1466 .Vb 1
1467 \& when ([qw(foo bar)] { ... }
1468 .Ve
1469 .PP
1470 This is somewhat equivalent to the C\-style switch statement's fallthrough
1471 functionality (not to be confused with \fIPerl's\fR fallthrough
1472 functionality\-\-see below), wherein the same block is used for several
1473 \&\f(CW\*(C`case\*(C'\fR statements.
1474 .PP
1475 Another useful shortcut is that, if you use a literal array or hash as the
1476 argument to \f(CW\*(C`given\*(C'\fR, it is turned into a reference. So \f(CWgiven(@foo)\fR is
1477 the same as \f(CWgiven(\e@foo)\fR, for example.
1478 .PP
1479 \&\f(CW\*(C`default\*(C'\fR behaves exactly like \f(CW\*(C`when(1 == 1)\*(C'\fR, which is
1480 to say that it always matches.
1481 .PP
1482 \fIBreaking out\fR
1483 .IX Subsection "Breaking out"
1484 .PP
1485 You can use the \f(CW\*(C`break\*(C'\fR keyword to break out of the enclosing
1486 \&\f(CW\*(C`given\*(C'\fR block. Every \f(CW\*(C`when\*(C'\fR block is implicitly ended with
1487 a \f(CW\*(C`break\*(C'\fR.
1488 .PP
1489 \fIFall-through\fR
1490 .IX Subsection "Fall-through"
1491 .PP
1492 You can use the \f(CW\*(C`continue\*(C'\fR keyword to fall through from one
1493 case to the next immediate \f(CW\*(C`when\*(C'\fR or \f(CW\*(C`default\*(C'\fR:
1494 .PP
1495 .Vb 5
1496 \& given($foo) {
1497 \& when (/x/) { say \*(Aq$foo contains an x\*(Aq; continue }
1498 \& when (/y/) { say \*(Aq$foo contains a y\*(Aq }
1499 \& default { say \*(Aq$foo does not contain a y\*(Aq }
1500 \& }
1501 .Ve
1502 .PP
1503 \fIReturn value\fR
1504 .IX Subsection "Return value"
1505 .PP
1506 When a \f(CW\*(C`given\*(C'\fR statement is also a valid expression (for example,
1507 when it's the last statement of a block), it evaluates to:
1508 .IP \(bu 4
1509 An empty list as soon as an explicit \f(CW\*(C`break\*(C'\fR is encountered.
1510 .IP \(bu 4
1511 The value of the last evaluated expression of the successful
1512 \&\f(CW\*(C`when\*(C'\fR/\f(CW\*(C`default\*(C'\fR clause, if there happens to be one.
1513 .IP \(bu 4
1514 The value of the last evaluated expression of the \f(CW\*(C`given\*(C'\fR block if no
1515 condition is true.
1516 .PP
1517 In both last cases, the last expression is evaluated in the context that
1518 was applied to the \f(CW\*(C`given\*(C'\fR block.
1519 .PP
1520 Note that, unlike \f(CW\*(C`if\*(C'\fR and \f(CW\*(C`unless\*(C'\fR, failed \f(CW\*(C`when\*(C'\fR statements always
1521 evaluate to an empty list.
1522 .PP
1523 .Vb 8
1524 \& my $price = do {
1525 \& given ($item) {
1526 \& when (["pear", "apple"]) { 1 }
1527 \& break when "vote"; # My vote cannot be bought
1528 \& 1e10 when /Mona Lisa/;
1529 \& "unknown";
1530 \& }
1531 \& };
1532 .Ve
1533 .PP
1534 Currently, \f(CW\*(C`given\*(C'\fR blocks can't always
1535 be used as proper expressions. This
1536 may be addressed in a future version of Perl.
1537 .PP
1538 \fISwitching in a loop\fR
1539 .IX Subsection "Switching in a loop"
1540 .PP
1541 Instead of using \f(CWgiven()\fR, you can use a \f(CWforeach()\fR loop.
1542 For example, here's one way to count how many times a particular
1543 string occurs in an array:
1544 .PP
1545 .Vb 6
1546 \& use v5.10.1;
1547 \& my $count = 0;
1548 \& for (@array) {
1549 \& when ("foo") { ++$count }
1550 \& }
1551 \& print "\e@array contains $count copies of \*(Aqfoo\*(Aq\en";
1552 .Ve
1553 .PP
1554 Or in a more recent version:
1555 .PP
1556 .Vb 6
1557 \& use v5.14;
1558 \& my $count = 0;
1559 \& for (@array) {
1560 \& ++$count when "foo";
1561 \& }
1562 \& print "\e@array contains $count copies of \*(Aqfoo\*(Aq\en";
1563 .Ve
1564 .PP
1565 At the end of all \f(CW\*(C`when\*(C'\fR blocks, there is an implicit \f(CW\*(C`next\*(C'\fR.
1566 You can override that with an explicit \f(CW\*(C`last\*(C'\fR if you're
1567 interested in only the first match alone.
1568 .PP
1569 This doesn't work if you explicitly specify a loop variable, as
1570 in \f(CW\*(C`for $item (@array)\*(C'\fR. You have to use the default variable \f(CW$_\fR.
1571 .PP
1572 \fIDifferences from Raku\fR
1573 .IX Subsection "Differences from Raku"
1574 .PP
1575 The Perl 5 smartmatch and \f(CW\*(C`given\*(C'\fR/\f(CW\*(C`when\*(C'\fR constructs are not compatible
1576 with their Raku analogues. The most visible difference and least
1577 important difference is that, in Perl 5, parentheses are required around
1578 the argument to \f(CWgiven()\fR and \f(CWwhen()\fR (except when this last one is used
1579 as a statement modifier). Parentheses in Raku are always optional in a
1580 control construct such as \f(CWif()\fR, \f(CWwhile()\fR, or \f(CWwhen()\fR; they can't be
1581 made optional in Perl 5 without a great deal of potential confusion,
1582 because Perl 5 would parse the expression
1583 .PP
1584 .Vb 3
1585 \& given $foo {
1586 \& ...
1587 \& }
1588 .Ve
1589 .PP
1590 as though the argument to \f(CW\*(C`given\*(C'\fR were an element of the hash
1591 \&\f(CW%foo\fR, interpreting the braces as hash-element syntax.
1592 .PP
1593 However, there are many, many other differences. For example,
1594 this works in Perl 5:
1595 .PP
1596 .Vb 2
1597 \& use v5.12;
1598 \& my @primary = ("red", "blue", "green");
1599 \&
1600 \& if (@primary ~~ "red") {
1601 \& say "primary smartmatches red";
1602 \& }
1603 \&
1604 \& if ("red" ~~ @primary) {
1605 \& say "red smartmatches primary";
1606 \& }
1607 \&
1608 \& say "that\*(Aqs all, folks!";
1609 .Ve
1610 .PP
1611 But it doesn't work at all in Raku. Instead, you should
1612 use the (parallelizable) \f(CW\*(C`any\*(C'\fR operator:
1613 .PP
1614 .Vb 3
1615 \& if any(@primary) eq "red" {
1616 \& say "primary smartmatches red";
1617 \& }
1618 \&
1619 \& if "red" eq any(@primary) {
1620 \& say "red smartmatches primary";
1621 \& }
1622 .Ve
1623 .PP
1624 The table of smartmatches in "Smartmatch Operator" in perlop is not
1625 identical to that proposed by the Raku specification, mainly due to
1626 differences between Raku's and Perl 5's data models, but also because
1627 the Raku spec has changed since Perl 5 rushed into early adoption.
1628 .PP
1629 In Raku, \f(CWwhen()\fR will always do an implicit smartmatch with its
1630 argument, while in Perl 5 it is convenient (albeit potentially confusing) to
1631 suppress this implicit smartmatch in various rather loosely-defined
1632 situations, as roughly outlined above. (The difference is largely because
1633 Perl 5 does not have, even internally, a boolean type.)