Debian Codegraph @

upstream/fedora-44/man1/perlsyn.1

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