This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perlapi: Consolidate sv_catpv-ish entries
[perl5.git] / pod / perlsyn.pod
CommitLineData
a0d0e21e 1=head1 NAME
d74e8afc 2X<syntax>
a0d0e21e
LW
3
4perlsyn - Perl syntax
5
6=head1 DESCRIPTION
7
6014d0cb 8A Perl program consists of a sequence of declarations and statements
c2f1e229 9which run from the top to the bottom. Loops, subroutines, and other
6014d0cb
MS
10control structures allow you to jump around within the code.
11
c2f1e229
TC
12Perl is a B<free-form> language: you can format and indent it however
13you like. Whitespace serves mostly to separate tokens, unlike
14languages like Python where it is an important part of the syntax,
15or Fortran where it is immaterial.
6014d0cb
MS
16
17Many of Perl's syntactic elements are B<optional>. Rather than
110b9c83 18requiring you to put parentheses around every function call and
6014d0cb
MS
19declare every variable, you can often leave such explicit elements off
20and Perl will figure out what you meant. This is known as B<Do What I
21Mean>, abbreviated B<DWIM>. It allows programmers to be B<lazy> and to
110b9c83 22code in a style with which they are comfortable.
6014d0cb
MS
23
24Perl B<borrows syntax> and concepts from many languages: awk, sed, C,
25Bourne Shell, Smalltalk, Lisp and even English. Other
26languages have borrowed syntax from Perl, particularly its regular
27expression extensions. So if you have programmed in another language
28you will see familiar pieces in Perl. They often work the same, but
29see L<perltrap> for information about how they differ.
a0d0e21e 30
0b8d69e9 31=head2 Declarations
d74e8afc 32X<declaration> X<undef> X<undefined> X<uninitialized>
0b8d69e9 33
cf48932e 34The only things you need to declare in Perl are report formats and
c2f1e229 35subroutines (and sometimes not even subroutines). A scalar variable holds
cf48932e
SF
36the undefined value (C<undef>) until it has been assigned a defined
37value, which is anything other than C<undef>. When used as a number,
38C<undef> is treated as C<0>; when used as a string, it is treated as
39the empty string, C<"">; and when used as a reference that isn't being
40assigned to, it is treated as an error. If you enable warnings,
41you'll be notified of an uninitialized value whenever you treat
42C<undef> as a string or a number. Well, usually. Boolean contexts,
43such as:
7bd1983c 44
7bd1983c
EM
45 if ($a) {}
46
a6b1f6d8
RGS
47are exempt from warnings (because they care about truth rather than
48definedness). Operators such as C<++>, C<-->, C<+=>,
c2f1e229 49C<-=>, and C<.=>, that operate on undefined variables such as:
7bd1983c 50
c2f1e229 51 undef $a;
7bd1983c
EM
52 $a++;
53
54are also always exempt from such warnings.
0b8d69e9 55
a0d0e21e 56A declaration can be put anywhere a statement can, but has no effect on
c2f1e229
TC
57the execution of the primary sequence of statements: declarations all
58take effect at compile time. All declarations are typically put at
54310121 59the beginning or the end of the script. However, if you're using
c2f1e229
TC
60lexically-scoped private variables created with C<my()>,
61C<state()>, or C<our()>, you'll have to make sure
4633a7c4 62your format or subroutine definition is within the same block scope
5f05dabc 63as the my if you expect to be able to access those private variables.
a0d0e21e 64
4633a7c4
LW
65Declaring a subroutine allows a subroutine name to be used as if it were a
66list operator from that point forward in the program. You can declare a
54310121 67subroutine without defining it by saying C<sub name>, thus:
d74e8afc 68X<subroutine, declaration>
a0d0e21e 69
54310121 70 sub myname;
15faabe4 71 $me = myname $0 or die "can't get myname";
a0d0e21e 72
c2f1e229
TC
73A bare declaration like that declares the function to be a list operator,
74not a unary operator, so you have to be careful to use parentheses (or
89a3b501 75C<or> instead of C<||>.) The C<||> operator binds too tightly to use after
c2f1e229
TC
76list operators; it becomes part of the last element. You can always use
77parentheses around the list operators arguments to turn the list operator
78back into something that behaves more like a function call. Alternatively,
79you can use the prototype C<($)> to turn the subroutine into a unary
80operator:
81
82 sub myname ($);
83 $me = myname $0 || die "can't get myname";
84
85That now parses as you'd expect, but you still ought to get in the habit of
86using parentheses in that situation. For more on prototypes, see
368fb018 87L<perlsub>.
a0d0e21e 88
4633a7c4
LW
89Subroutines declarations can also be loaded up with the C<require> statement
90or both loaded and imported into your namespace with a C<use> statement.
91See L<perlmod> for details on this.
a0d0e21e 92
4633a7c4
LW
93A statement sequence may contain declarations of lexically-scoped
94variables, but apart from declaring a variable name, the declaration acts
95like an ordinary statement, and is elaborated within the sequence of
96statements as if it were an ordinary statement. That means it actually
97has both compile-time and run-time effects.
a0d0e21e 98
6014d0cb 99=head2 Comments
d74e8afc 100X<comment> X<#>
6014d0cb
MS
101
102Text from a C<"#"> character until the end of the line is a comment,
103and is ignored. Exceptions include C<"#"> inside a string or regular
104expression.
105
6ec4bd10 106=head2 Simple Statements
d74e8afc 107X<statement> X<semicolon> X<expression> X<;>
a0d0e21e
LW
108
109The only kind of simple statement is an expression evaluated for its
c2f1e229 110side-effects. Every simple statement must be terminated with a
a0d0e21e 111semicolon, unless it is the final statement in a block, in which case
c2f1e229 112the semicolon is optional. But put the semicolon in anyway if the
f386e492 113block takes up more than one line, because you may eventually add
c2f1e229
TC
114another line. Note that there are operators like C<eval {}>, C<sub {}>, and
115C<do {}> that I<look> like compound statements, but aren't--they're just
116TERMs in an expression--and thus need an explicit termination when used
cf48932e
SF
117as the last item in a statement.
118
cf48932e 119=head2 Statement Modifiers
d74e8afc 120X<statement modifier> X<modifier> X<if> X<unless> X<while>
7896dde7 121X<until> X<when> X<foreach> X<for>
a0d0e21e
LW
122
123Any simple statement may optionally be followed by a I<SINGLE> modifier,
124just before the terminating semicolon (or block ending). The possible
125modifiers are:
126
127 if EXPR
128 unless EXPR
129 while EXPR
130 until EXPR
4f8ea571 131 for LIST
cf48932e 132 foreach LIST
7896dde7 133 when EXPR
cf48932e
SF
134
135The C<EXPR> following the modifier is referred to as the "condition".
136Its truth or falsehood determines how the modifier will behave.
137
138C<if> executes the statement once I<if> and only if the condition is
139true. C<unless> is the opposite, it executes the statement I<unless>
ef37f6f5
C
140the condition is true (that is, if the condition is false). See
141L<perldata/Scalar values> for definitions of true and false.
cf48932e
SF
142
143 print "Basset hounds got long ears" if length $ear >= 10;
144 go_outside() and play() unless $is_raining;
145
c2f1e229 146The C<for(each)> modifier is an iterator: it executes the statement once
cf48932e 147for each item in the LIST (with C<$_> aliased to each item in turn).
ec89cf10
DB
148There is no syntax to specify a C-style for loop or a lexically scoped
149iteration variable in this form.
cf48932e 150
c2f1e229 151 print "Hello $_!\n" for qw(world Dolly nurse);
cf48932e
SF
152
153C<while> repeats the statement I<while> the condition is true.
5e979393
Z
154Postfix C<while> has the same magic treatment of some kinds of condition
155that prefix C<while> has.
cf48932e
SF
156C<until> does the opposite, it repeats the statement I<until> the
157condition is true (or while the condition is false):
158
159 # Both of these count from 0 to 10.
160 print $i++ while $i <= 10;
161 print $j++ until $j > 10;
162
163The C<while> and C<until> modifiers have the usual "C<while> loop"
164semantics (conditional evaluated first), except when applied to a
c2f1e229 165C<do>-BLOCK (or to the Perl4 C<do>-SUBROUTINE statement), in
cf48932e 166which case the block executes once before the conditional is
c2f1e229
TC
167evaluated.
168
169This is so that you can write loops like:
a0d0e21e
LW
170
171 do {
15faabe4
SF
172 $line = <STDIN>;
173 ...
c2f1e229 174 } until !defined($line) || $line eq ".\n"
a0d0e21e 175
5a964f20
TC
176See L<perlfunc/do>. Note also that the loop control statements described
177later will I<NOT> work in this construct, because modifiers don't take
178loop labels. Sorry. You can always put another block inside of it
015aa1a8 179(for C<next>/C<redo>) or around it (for C<last>) to do that sort of thing.
d74e8afc 180X<next> X<last> X<redo>
5a964f20 181
015aa1a8
LM
182For C<next> or C<redo>, just double the braces:
183
5a964f20 184 do {{
15faabe4
SF
185 next if $x == $y;
186 # do something here
5a964f20
TC
187 }} until $x++ > $z;
188
015aa1a8 189For C<last>, you have to be more elaborate and put braces around it:
d74e8afc 190X<last>
5a964f20 191
015aa1a8
LM
192 {
193 do {
194 last if $x == $y**2;
195 # do something here
196 } while $x++ <= $z;
197 }
198
199If you need both C<next> and C<last>, you have to do both and also use a
200loop label:
201
15faabe4 202 LOOP: {
015aa1a8
LM
203 do {{
204 next if $x == $y;
205 last LOOP if $x == $y**2;
206 # do something here
207 }} until $x++ > $z;
5a964f20 208 }
a0d0e21e 209
c2f1e229
TC
210B<NOTE:> The behaviour of a C<my>, C<state>, or
211C<our> modified with a statement modifier conditional
212or loop construct (for example, C<my $x if ...>) is
457b36cb
MV
213B<undefined>. The value of the C<my> variable may be C<undef>, any
214previously assigned value, or possibly anything else. Don't rely on
215it. Future versions of perl might do something different from the
216version of perl you try it out on. Here be dragons.
d74e8afc 217X<my>
457b36cb 218
7896dde7
Z
219The C<when> modifier is an experimental feature that first appeared in Perl
2205.14. To use it, you should include a C<use v5.14> declaration.
221(Technically, it requires only the C<switch> feature, but that aspect of it
222was not available before 5.14.) Operative only from within a C<foreach>
223loop or a C<given> block, it executes the statement only if the smartmatch
224C<< $_ ~~ I<EXPR> >> is true. If the statement executes, it is followed by
225a C<next> from inside a C<foreach> and C<break> from inside a C<given>.
226
227Under the current implementation, the C<foreach> loop can be
228anywhere within the C<when> modifier's dynamic scope, but must be
229within the C<given> block's lexical scope. This restriction may
230be relaxed in a future release. See L</"Switch Statements"> below.
c2f1e229 231
6ec4bd10 232=head2 Compound Statements
d74e8afc 233X<statement, compound> X<block> X<bracket, curly> X<curly bracket> X<brace>
c2f1e229 234X<{> X<}> X<if> X<unless> X<given> X<while> X<until> X<foreach> X<for> X<continue>
a0d0e21e
LW
235
236In Perl, a sequence of statements that defines a scope is called a block.
237Sometimes a block is delimited by the file containing it (in the case
238of a required file, or the program as a whole), and sometimes a block
239is delimited by the extent of a string (in the case of an eval).
240
55771418
Z
241But generally, a block is delimited by curly brackets, also known as
242braces. We will call this syntactic construct a BLOCK. Because enclosing
243braces are also the syntax for hash reference constructor expressions
244(see L<perlref>), you may occasionally need to disambiguate by placing a
245C<;> immediately after an opening brace so that Perl realises the brace
246is the start of a block. You will more frequently need to disambiguate
247the other way, by placing a C<+> immediately before an opening brace to
248force it to be interpreted as a hash reference constructor expression.
249It is considered good style to use these disambiguating mechanisms
250liberally, not only when Perl would otherwise guess incorrectly.
a0d0e21e
LW
251
252The following compound statements may be used to control flow:
253
254 if (EXPR) BLOCK
255 if (EXPR) BLOCK else BLOCK
c2f1e229 256 if (EXPR) BLOCK elsif (EXPR) BLOCK ...
a0d0e21e 257 if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
c2f1e229 258
62d98eed
RU
259 unless (EXPR) BLOCK
260 unless (EXPR) BLOCK else BLOCK
c2f1e229 261 unless (EXPR) BLOCK elsif (EXPR) BLOCK ...
d27f8d4b 262 unless (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
c2f1e229
TC
263
264 given (EXPR) BLOCK
265
a0d0e21e
LW
266 LABEL while (EXPR) BLOCK
267 LABEL while (EXPR) BLOCK continue BLOCK
c2f1e229 268
5ec6d87f
EA
269 LABEL until (EXPR) BLOCK
270 LABEL until (EXPR) BLOCK continue BLOCK
c2f1e229 271
a0d0e21e 272 LABEL for (EXPR; EXPR; EXPR) BLOCK
7808b687
AB
273 LABEL for VAR (LIST) BLOCK
274 LABEL for VAR (LIST) BLOCK continue BLOCK
c2f1e229 275
7808b687 276 LABEL foreach (EXPR; EXPR; EXPR) BLOCK
748a9306 277 LABEL foreach VAR (LIST) BLOCK
b303ae78 278 LABEL foreach VAR (LIST) BLOCK continue BLOCK
c2f1e229
TC
279
280 LABEL BLOCK
a0d0e21e 281 LABEL BLOCK continue BLOCK
c2f1e229 282
43f66a76 283 PHASE BLOCK
a0d0e21e 284
7896dde7
Z
285The experimental C<given> statement is I<not automatically enabled>; see
286L</"Switch Statements"> below for how to do so, and the attendant caveats.
c2f1e229
TC
287
288Unlike in C and Pascal, in Perl these are all defined in terms of BLOCKs,
a0d0e21e
LW
289not statements. This means that the curly brackets are I<required>--no
290dangling statements allowed. If you want to write conditionals without
c2f1e229 291curly brackets, there are several other ways to do it. The following
a0d0e21e
LW
292all do the same thing:
293
c2f1e229 294 if (!open(FOO)) { die "Can't open $FOO: $!" }
a0d0e21e 295 die "Can't open $FOO: $!" unless open(FOO);
c2f1e229
TC
296 open(FOO) || die "Can't open $FOO: $!";
297 open(FOO) ? () : die "Can't open $FOO: $!";
15faabe4 298 # a bit exotic, that last one
a0d0e21e 299
5f05dabc 300The C<if> statement is straightforward. Because BLOCKs are always
a0d0e21e
LW
301bounded by curly brackets, there is never any ambiguity about which
302C<if> an C<else> goes with. If you use C<unless> in place of C<if>,
89a3b501
FC
303the sense of the test is reversed. Like C<if>, C<unless> can be followed
304by C<else>. C<unless> can even be followed by one or more C<elsif>
d27f8d4b
JV
305statements, though you may want to think twice before using that particular
306language construct, as everyone reading your code will have to think at least
307twice before they can understand what's going on.
a0d0e21e
LW
308
309The C<while> statement executes the block as long as the expression is
77fae439 310true.
1d5653dd
RGS
311The C<until> statement executes the block as long as the expression is
312false.
b78218b7
GS
313The LABEL is optional, and if present, consists of an identifier followed
314by a colon. The LABEL identifies the loop for the loop control
315statements C<next>, C<last>, and C<redo>.
316If the LABEL is omitted, the loop control statement
4633a7c4
LW
317refers to the innermost enclosing loop. This may include dynamically
318looking back your call-stack at run time to find the LABEL. Such
9f1b1f2d 319desperate behavior triggers a warning if you use the C<use warnings>
a2293a43 320pragma or the B<-w> flag.
4633a7c4 321
5e979393
Z
322If the condition expression of a C<while> statement is based
323on any of a group of iterative expression types then it gets
324some magic treatment. The affected iterative expression types
325are L<C<readline>|perlfunc/readline EXPR>, the L<C<< <FILEHANDLE>
326>>|perlop/"I/O Operators"> input operator, L<C<readdir>|perlfunc/readdir
327DIRHANDLE>, L<C<glob>|perlfunc/glob EXPR>, the L<C<< <PATTERN>
328>>|perlop/"I/O Operators"> globbing operator, and L<C<each>|perlfunc/each
329HASH>. If the condition expression is one of these expression types, then
330the value yielded by the iterative operator will be implicitly assigned
331to C<$_>. If the condition expression is one of these expression types
332or an explicit assignment of one of them to a scalar, then the condition
333actually tests for definedness of the expression's value, not for its
334regular truth value.
335
4633a7c4 336If there is a C<continue> BLOCK, it is always executed just before the
6ec4bd10
MS
337conditional is about to be evaluated again. Thus it can be used to
338increment a loop variable, even when the loop has been continued via
339the C<next> statement.
4633a7c4 340
ae999eaf 341When a block is preceded by a compilation phase keyword such as C<BEGIN>,
43f66a76
DG
342C<END>, C<INIT>, C<CHECK>, or C<UNITCHECK>, then the block will run only
343during the corresponding phase of execution. See L<perlmod> for more details.
344
88e1f1a2 345Extension modules can also hook into the Perl parser to define new
c2f1e229 346kinds of compound statements. These are introduced by a keyword which
6a0969e5 347the extension recognizes, and the syntax following the keyword is
88e1f1a2
JV
348defined entirely by the extension. If you are an implementor, see
349L<perlapi/PL_keyword_plugin> for the mechanism. If you are using such
350a module, see the module's documentation for details of the syntax that
351it defines.
352
4633a7c4 353=head2 Loop Control
d74e8afc 354X<loop control> X<loop, control> X<next> X<last> X<redo> X<continue>
4633a7c4 355
6ec4bd10 356The C<next> command starts the next iteration of the loop:
4633a7c4
LW
357
358 LINE: while (<STDIN>) {
15faabe4
SF
359 next LINE if /^#/; # discard comments
360 ...
4633a7c4
LW
361 }
362
6ec4bd10 363The C<last> command immediately exits the loop in question. The
4633a7c4
LW
364C<continue> block, if any, is not executed:
365
366 LINE: while (<STDIN>) {
15faabe4
SF
367 last LINE if /^$/; # exit when done with header
368 ...
4633a7c4
LW
369 }
370
371The C<redo> command restarts the loop block without evaluating the
372conditional again. The C<continue> block, if any, is I<not> executed.
373This command is normally used by programs that want to lie to themselves
374about what was just input.
375
376For example, when processing a file like F</etc/termcap>.
377If your input lines might end in backslashes to indicate continuation, you
378want to skip ahead and get the next record.
379
380 while (<>) {
15faabe4
SF
381 chomp;
382 if (s/\\$//) {
383 $_ .= <>;
384 redo unless eof();
385 }
386 # now process $_
54310121 387 }
4633a7c4 388
c2f1e229 389which is Perl shorthand for the more explicitly written version:
4633a7c4 390
54310121 391 LINE: while (defined($line = <ARGV>)) {
15faabe4
SF
392 chomp($line);
393 if ($line =~ s/\\$//) {
394 $line .= <ARGV>;
395 redo LINE unless eof(); # not eof(ARGV)!
396 }
397 # now process $line
54310121 398 }
4633a7c4 399
36e7a065
AMS
400Note that if there were a C<continue> block on the above code, it would
401get executed only on lines discarded by the regex (since redo skips the
89a3b501 402continue block). A continue block is often used to reset line counters
499a640d 403or C<m?pat?> one-time matches:
4633a7c4 404
5a964f20
TC
405 # inspired by :1,$g/fred/s//WILMA/
406 while (<>) {
15faabe4
SF
407 m?(fred)? && s//WILMA $1 WILMA/;
408 m?(barney)? && s//BETTY $1 BETTY/;
409 m?(homer)? && s//MARGE $1 MARGE/;
5a964f20 410 } continue {
15faabe4
SF
411 print "$ARGV $.: $_";
412 close ARGV if eof; # reset $.
413 reset if eof; # reset ?pat?
4633a7c4
LW
414 }
415
a0d0e21e
LW
416If the word C<while> is replaced by the word C<until>, the sense of the
417test is reversed, but the conditional is still tested before the first
418iteration.
419
c2f1e229 420Loop control statements don't work in an C<if> or C<unless>, since
5a964f20
TC
421they aren't loops. You can double the braces to make them such, though.
422
423 if (/pattern/) {{
15faabe4
SF
424 last if /fred/;
425 next if /barney/; # same effect as "last",
426 # but doesn't document as well
427 # do something here
5a964f20
TC
428 }}
429
7bd1983c 430This is caused by the fact that a block by itself acts as a loop that
88bd7502 431executes once, see L</"Basic BLOCKs">.
7bd1983c 432
5b23ba8b
MG
433The form C<while/if BLOCK BLOCK>, available in Perl 4, is no longer
434available. Replace any occurrence of C<if BLOCK> by C<if (do BLOCK)>.
4633a7c4 435
cb1a09d0 436=head2 For Loops
d74e8afc 437X<for> X<foreach>
a0d0e21e 438
b78df5de 439Perl's C-style C<for> loop works like the corresponding C<while> loop;
cb1a09d0 440that means that this:
a0d0e21e
LW
441
442 for ($i = 1; $i < 10; $i++) {
15faabe4 443 ...
a0d0e21e
LW
444 }
445
cb1a09d0 446is the same as this:
a0d0e21e
LW
447
448 $i = 1;
449 while ($i < 10) {
15faabe4 450 ...
a0d0e21e 451 } continue {
15faabe4 452 $i++;
a0d0e21e
LW
453 }
454
b78df5de
JA
455There is one minor difference: if variables are declared with C<my>
456in the initialization section of the C<for>, the lexical scope of
457those variables is exactly the C<for> loop (the body of the loop
458and the control sections).
d74e8afc 459X<my>
55497cff 460
62bd8e4f
PM
461As a special case, if the test in the C<for> loop (or the corresponding
462C<while> loop) is empty, it is treated as true. That is, both
463
464 for (;;) {
15faabe4 465 ...
62bd8e4f
PM
466 }
467
468and
469
470 while () {
15faabe4 471 ...
62bd8e4f
PM
472 }
473
474are treated as infinite loops.
475
cb1a09d0
AD
476Besides the normal array index looping, C<for> can lend itself
477to many other interesting applications. Here's one that avoids the
54310121 478problem you get into if you explicitly test for end-of-file on
479an interactive file descriptor causing your program to appear to
cb1a09d0 480hang.
d74e8afc 481X<eof> X<end-of-file> X<end of file>
cb1a09d0
AD
482
483 $on_a_tty = -t STDIN && -t STDOUT;
484 sub prompt { print "yes? " if $on_a_tty }
485 for ( prompt(); <STDIN>; prompt() ) {
15faabe4 486 # do something
54310121 487 }
cb1a09d0 488
5e979393
Z
489The condition expression of a C<for> loop gets the same magic treatment of
490C<readline> et al that the condition expression of a C<while> loop gets.
00cb5da1 491
cb1a09d0 492=head2 Foreach Loops
d74e8afc 493X<for> X<foreach>
cb1a09d0 494
82848c10 495The C<foreach> loop iterates over a normal list value and sets the scalar
55497cff 496variable VAR to be each element of the list in turn. If the variable
497is preceded with the keyword C<my>, then it is lexically scoped, and
498is therefore visible only within the loop. Otherwise, the variable is
499implicitly local to the loop and regains its former value upon exiting
500the loop. If the variable was previously declared with C<my>, it uses
501that variable instead of the global one, but it's still localized to
6a0969e5 502the loop. This implicit localization occurs I<only> in a C<foreach>
5c502d37 503loop.
d74e8afc 504X<my> X<local>
4633a7c4
LW
505
506The C<foreach> keyword is actually a synonym for the C<for> keyword, so
c2f1e229 507you can use either. If VAR is omitted, C<$_> is set to each value.
d74e8afc 508X<$_>
c5674021
PDF
509
510If any element of LIST is an lvalue, you can modify it by modifying
511VAR inside the loop. Conversely, if any element of LIST is NOT an
512lvalue, any attempt to modify that element will fail. In other words,
513the C<foreach> loop index variable is an implicit alias for each item
514in the list that you're looping over.
d74e8afc 515X<alias>
302617ea
MG
516
517If any part of LIST is an array, C<foreach> will get very confused if
518you add or remove elements within the loop body, for example with
519C<splice>. So don't do that.
d74e8afc 520X<splice>
302617ea
MG
521
522C<foreach> probably won't do what you expect if VAR is a tied or other
523special variable. Don't do that either.
4633a7c4 524
82848c10
FC
525As of Perl 5.22, there is an experimental variant of this loop that accepts
526a variable preceded by a backslash for VAR, in which case the items in the
527LIST must be references. The backslashed variable will become an alias
528to each referenced item in the LIST, which must be of the correct type.
529The variable needn't be a scalar in this case, and the backslash may be
baabe3fb 530followed by C<my>. To use this form, you must enable the C<refaliasing>
82848c10
FC
531feature via C<use feature>. (See L<feature>. See also L<perlref/Assigning
532to References>.)
533
748a9306 534Examples:
a0d0e21e 535
4633a7c4 536 for (@ary) { s/foo/bar/ }
a0d0e21e 537
96f2dc66 538 for my $elem (@elements) {
15faabe4 539 $elem *= 2;
a0d0e21e
LW
540 }
541
c2f1e229 542 for $count (reverse(1..10), "BOOM") {
15faabe4
SF
543 print $count, "\n";
544 sleep(1);
a0d0e21e
LW
545 }
546
547 for (1..15) { print "Merry Christmas\n"; }
548
4633a7c4 549 foreach $item (split(/:[\\\n:]*/, $ENV{TERMCAP})) {
15faabe4 550 print "Item: $item\n";
a0d0e21e
LW
551 }
552
baabe3fb
FC
553 use feature "refaliasing";
554 no warnings "experimental::refaliasing";
82848c10 555 foreach \my %hash (@array_of_hash_references) {
15faabe4 556 # do something which each %hash
82848c10
FC
557 }
558
4633a7c4
LW
559Here's how a C programmer might code up a particular algorithm in Perl:
560
55497cff 561 for (my $i = 0; $i < @ary1; $i++) {
15faabe4
SF
562 for (my $j = 0; $j < @ary2; $j++) {
563 if ($ary1[$i] > $ary2[$j]) {
564 last; # can't go to outer :-(
565 }
566 $ary1[$i] += $ary2[$j];
567 }
568 # this is where that last takes me
4633a7c4
LW
569 }
570
184e9718 571Whereas here's how a Perl programmer more comfortable with the idiom might
cb1a09d0 572do it:
4633a7c4 573
96f2dc66
GS
574 OUTER: for my $wid (@ary1) {
575 INNER: for my $jet (@ary2) {
15faabe4
SF
576 next OUTER if $wid > $jet;
577 $wid += $jet;
578 }
579 }
4633a7c4 580
cb1a09d0
AD
581See how much easier this is? It's cleaner, safer, and faster. It's
582cleaner because it's less noisy. It's safer because if code gets added
c07a80fd 583between the inner and outer loops later on, the new code won't be
5f05dabc 584accidentally executed. The C<next> explicitly iterates the other loop
c07a80fd 585rather than merely terminating the inner one. And it's faster because
586Perl executes a C<foreach> statement more rapidly than it would the
0d86a399 587equivalent C-style C<for> loop.
4633a7c4 588
739ba955
RS
589Perceptive Perl hackers may have noticed that a C<for> loop has a return
590value, and that this value can be captured by wrapping the loop in a C<do>
591block. The reward for this discovery is this cautionary advice: The
592return value of a C<for> loop is unspecified and may change without notice.
593Do not rely on it.
594
0d863452
RH
595=head2 Basic BLOCKs
596X<block>
4633a7c4 597
55497cff 598A BLOCK by itself (labeled or not) is semantically equivalent to a
599loop that executes once. Thus you can use any of the loop control
600statements in it to leave or restart the block. (Note that this is
601I<NOT> true in C<eval{}>, C<sub{}>, or contrary to popular belief
602C<do{}> blocks, which do I<NOT> count as loops.) The C<continue>
603block is optional.
4633a7c4 604
27cec4bd 605The BLOCK construct can be used to emulate case structures.
a0d0e21e
LW
606
607 SWITCH: {
15faabe4
SF
608 if (/^abc/) { $abc = 1; last SWITCH; }
609 if (/^def/) { $def = 1; last SWITCH; }
610 if (/^xyz/) { $xyz = 1; last SWITCH; }
611 $nothing = 1;
a0d0e21e
LW
612 }
613
7896dde7
Z
614You'll also find that C<foreach> loop used to create a topicalizer
615and a switch:
c2f1e229
TC
616
617 SWITCH:
618 for ($var) {
15faabe4
SF
619 if (/^abc/) { $abc = 1; last SWITCH; }
620 if (/^def/) { $def = 1; last SWITCH; }
621 if (/^xyz/) { $xyz = 1; last SWITCH; }
622 $nothing = 1;
c2f1e229
TC
623 }
624
625Such constructs are quite frequently used, both because older versions of
626Perl had no official C<switch> statement, and also because the new version
7896dde7 627described immediately below remains experimental and can sometimes be confusing.
83df6a1d 628
c2f1e229 629=head2 Switch Statements
fd4f5766 630
7896dde7 631X<switch> X<case> X<given> X<when> X<default>
83df6a1d 632
7896dde7
Z
633Starting from Perl 5.10.1 (well, 5.10.0, but it didn't work
634right), you can say
83df6a1d 635
27cec4bd 636 use feature "switch";
a0d0e21e 637
7896dde7 638to enable an experimental switch feature. This is loosely based on an
17b35041 639old version of a Raku proposal, but it no longer resembles the Raku
7896dde7 640construct. You also get the switch feature whenever you declare that your
c2f1e229
TC
641code prefers to run under a version of Perl that is 5.10 or later. For
642example:
643
644 use v5.14;
645
7896dde7
Z
646Under the "switch" feature, Perl gains the experimental keywords
647C<given>, C<when>, C<default>, C<continue>, and C<break>.
648Starting from Perl 5.16, one can prefix the switch
649keywords with C<CORE::> to access the feature without a C<use feature>
650statement. The keywords C<given> and
651C<when> are analogous to C<switch> and
652C<case> in other languages -- though C<continue> is not -- so the code
653in the previous section could be rewritten as
c2f1e229
TC
654
655 use v5.10.1;
7896dde7
Z
656 for ($var) {
657 when (/^abc/) { $abc = 1 }
658 when (/^def/) { $def = 1 }
659 when (/^xyz/) { $xyz = 1 }
660 default { $nothing = 1 }
c2f1e229
TC
661 }
662
7896dde7
Z
663The C<foreach> is the non-experimental way to set a topicalizer.
664If you wish to use the highly experimental C<given>, that could be
665written like this:
0d863452 666
7896dde7 667 use v5.10.1;
c2f1e229 668 given ($var) {
7896dde7
Z
669 when (/^abc/) { $abc = 1 }
670 when (/^def/) { $def = 1 }
671 when (/^xyz/) { $xyz = 1 }
672 default { $nothing = 1 }
c2f1e229
TC
673 }
674
7896dde7 675As of 5.14, that can also be written this way:
0d863452 676
7896dde7
Z
677 use v5.14;
678 for ($var) {
679 $abc = 1 when /^abc/;
680 $def = 1 when /^def/;
681 $xyz = 1 when /^xyz/;
682 default { $nothing = 1 }
a0d0e21e
LW
683 }
684
7896dde7 685Or if you don't care to play it safe, like this:
c2f1e229 686
7896dde7
Z
687 use v5.14;
688 given ($var) {
689 $abc = 1 when /^abc/;
690 $def = 1 when /^def/;
691 $xyz = 1 when /^xyz/;
692 default { $nothing = 1 }
693 }
64805db9 694
7896dde7
Z
695The arguments to C<given> and C<when> are in scalar context,
696and C<given> assigns the C<$_> variable its topic value.
697
698Exactly what the I<EXPR> argument to C<when> does is hard to describe
699precisely, but in general, it tries to guess what you want done. Sometimes
700it is interpreted as C<< $_ ~~ I<EXPR> >>, and sometimes it is not. It
701also behaves differently when lexically enclosed by a C<given> block than
702it does when dynamically enclosed by a C<foreach> loop. The rules are far
703too difficult to understand to be described here. See L</"Experimental Details
704on given and when"> later on.
705
706Due to an unfortunate bug in how C<given> was implemented between Perl 5.10
707and 5.16, under those implementations the version of C<$_> governed by
708C<given> is merely a lexically scoped copy of the original, not a
709dynamically scoped alias to the original, as it would be if it were a
17b35041 710C<foreach> or under both the original and the current Raku language
7896dde7
Z
711specification. This bug was fixed in Perl 5.18 (and lexicalized C<$_> itself
712was removed in Perl 5.24).
713
714If your code still needs to run on older versions,
715stick to C<foreach> for your topicalizer and
716you will be less unhappy.
c2f1e229
TC
717
718=head2 Goto
719X<goto>
720
721Although not for the faint of heart, Perl does support a C<goto>
722statement. There are three forms: C<goto>-LABEL, C<goto>-EXPR, and
723C<goto>-&NAME. A loop's LABEL is not actually a valid target for
724a C<goto>; it's just the name of the loop.
725
726The C<goto>-LABEL form finds the statement labeled with LABEL and resumes
727execution there. It may not be used to go into any construct that
728requires initialization, such as a subroutine or a C<foreach> loop. It
729also can't be used to go into a construct that is optimized away. It
730can be used to go almost anywhere else within the dynamic scope,
731including out of subroutines, but it's usually better to use some other
732construct such as C<last> or C<die>. The author of Perl has never felt the
733need to use this form of C<goto> (in Perl, that is--C is another matter).
734
735The C<goto>-EXPR form expects a label name, whose scope will be resolved
736dynamically. This allows for computed C<goto>s per FORTRAN, but isn't
737necessarily recommended if you're optimizing for maintainability:
738
739 goto(("FOO", "BAR", "GLARCH")[$i]);
740
741The C<goto>-&NAME form is highly magical, and substitutes a call to the
742named subroutine for the currently running subroutine. This is used by
743C<AUTOLOAD()> subroutines that wish to load another subroutine and then
744pretend that the other subroutine had been called in the first place
745(except that any modifications to C<@_> in the current subroutine are
746propagated to the other subroutine.) After the C<goto>, not even C<caller()>
747will be able to tell that this routine was called first.
748
749In almost all cases like this, it's usually a far, far better idea to use the
750structured control flow mechanisms of C<next>, C<last>, or C<redo> instead of
751resorting to a C<goto>. For certain applications, the catch and throw pair of
752C<eval{}> and die() for exception processing can also be a prudent approach.
753
754=head2 The Ellipsis Statement
755X<...>
756X<... statement>
757X<ellipsis operator>
758X<elliptical statement>
759X<unimplemented statement>
760X<unimplemented operator>
761X<yada-yada>
81104cdf
FC
762X<yada-yada operator>
763X<... operator>
764X<whatever operator>
765X<triple-dot operator>
c2f1e229
TC
766
767Beginning in Perl 5.12, Perl accepts an ellipsis, "C<...>", as a
29d69c3c 768placeholder for code that you haven't implemented yet.
b735b77b 769When Perl 5.12 or later encounters an ellipsis statement, it parses this
c2f1e229
TC
770without error, but if and when you should actually try to execute it, Perl
771throws an exception with the text C<Unimplemented>:
772
9dba9ce0 773 use v5.12;
c2f1e229
TC
774 sub unimplemented { ... }
775 eval { unimplemented() };
9dba9ce0 776 if ($@ =~ /^Unimplemented at /) {
15faabe4 777 say "I found an ellipsis!";
c2f1e229
TC
778 }
779
29d69c3c
Z
780You can only use the elliptical statement to stand in for a complete
781statement. Syntactically, "C<...;>" is a complete statement, but,
782as with other kinds of semicolon-terminated statement, the semicolon
783may be omitted if "C<...>" appears immediately before a closing brace.
784These examples show how the ellipsis works:
c2f1e229
TC
785
786 use v5.12;
787 { ... }
788 sub foo { ... }
789 ...;
790 eval { ... };
791 sub somemeth {
15faabe4
SF
792 my $self = shift;
793 ...;
c2f1e229
TC
794 }
795 $x = do {
15faabe4
SF
796 my $n;
797 ...;
798 say "Hurrah!";
799 $n;
c2f1e229
TC
800 };
801
802The elliptical statement cannot stand in for an expression that
29d69c3c 803is part of a larger statement.
c2f1e229
TC
804These examples of attempts to use an ellipsis are syntax errors:
805
806 use v5.12;
807
808 print ...;
809 open(my $fh, ">", "/dev/passwd") or ...;
810 if ($condition && ... ) { say "Howdy" };
29d69c3c
Z
811 ... if $a > $b;
812 say "Cromulent" if ...;
813 $flub = 5 + ...;
c2f1e229
TC
814
815There are some cases where Perl can't immediately tell the difference
816between an expression and a statement. For instance, the syntax for a
817block and an anonymous hash reference constructor look the same unless
818there's something in the braces to give Perl a hint. The ellipsis is a
29d69c3c 819syntax error if Perl doesn't guess that the C<{ ... }> is a block.
12d22d1f 820Inside your block, you can use a C<;> before the ellipsis to denote that the
29d69c3c 821C<{ ... }> is a block and not a hash reference constructor.
c2f1e229
TC
822
823Note: Some folks colloquially refer to this bit of punctuation as a
81104cdf 824"yada-yada" or "triple-dot", but its true name
84539229 825is actually an ellipsis.
c2f1e229
TC
826
827=head2 PODs: Embedded Documentation
828X<POD> X<documentation>
829
830Perl has a mechanism for intermixing documentation with source code.
831While it's expecting the beginning of a new statement, if the compiler
832encounters a line that begins with an equal sign and a word, like this
833
834 =head1 Here There Be Pods!
835
836Then that text and all remaining text up through and including a line
837beginning with C<=cut> will be ignored. The format of the intervening
838text is described in L<perlpod>.
839
840This allows you to intermix your source code
841and your documentation text freely, as in
842
843 =item snazzle($)
844
845 The snazzle() function will behave in the most spectacular
846 form that you can possibly imagine, not even excepting
847 cybernetic pyrotechnics.
848
849 =cut back to the compiler, nuff of this pod stuff!
850
851 sub snazzle($) {
15faabe4
SF
852 my $thingie = shift;
853 .........
c2f1e229
TC
854 }
855
856Note that pod translators should look at only paragraphs beginning
857with a pod directive (it makes parsing easier), whereas the compiler
858actually knows to look for pod escapes even in the middle of a
859paragraph. This means that the following secret stuff will be
860ignored by both the compiler and the translators.
861
862 $a=3;
863 =secret stuff
864 warn "Neither POD nor CODE!?"
865 =cut back
866 print "got $a\n";
867
868You probably shouldn't rely upon the C<warn()> being podded out forever.
869Not all pod translators are well-behaved in this regard, and perhaps
870the compiler will become pickier.
871
872One may also use pod directives to quickly comment out a section
873of code.
874
875=head2 Plain Old Comments (Not!)
876X<comment> X<line> X<#> X<preprocessor> X<eval>
877
878Perl can process line directives, much like the C preprocessor. Using
879this, one can control Perl's idea of filenames and line numbers in
880error or warning messages (especially for strings that are processed
881with C<eval()>). The syntax for this mechanism is almost the same as for
882most C preprocessors: it matches the regular expression
883
884 # example: '# line 42 "new_filename.plx"'
885 /^\# \s*
886 line \s+ (\d+) \s*
887 (?:\s("?)([^"]+)\g2)? \s*
888 $/x
889
890with C<$1> being the line number for the next line, and C<$3> being
89a3b501 891the optional filename (specified with or without quotes). Note that
c2f1e229
TC
892no whitespace may precede the C<< # >>, unlike modern C preprocessors.
893
894There is a fairly obvious gotcha included with the line directive:
895Debuggers and profilers will only show the last source line to appear
896at a particular line number in a given file. Care should be taken not
897to cause line number collisions in code you'd like to debug later.
898
899Here are some examples that you should be able to type into your command
900shell:
901
902 % perl
903 # line 200 "bzzzt"
904 # the '#' on the previous line must be the first char on line
905 die 'foo';
906 __END__
907 foo at bzzzt line 201.
908
909 % perl
910 # line 200 "bzzzt"
911 eval qq[\n#line 2001 ""\ndie 'foo']; print $@;
912 __END__
913 foo at - line 2001.
914
915 % perl
916 eval qq[\n#line 200 "foo bar"\ndie 'foo']; print $@;
917 __END__
918 foo at foo bar line 200.
919
920 % perl
921 # line 345 "goop"
922 eval "\n#line " . __LINE__ . ' "' . __FILE__ ."\"\ndie 'foo'";
923 print $@;
924 __END__
925 foo at goop line 345.
926
7896dde7
Z
927=head2 Experimental Details on given and when
928
929As previously mentioned, the "switch" feature is considered highly
930experimental; it is subject to change with little notice. In particular,
931C<when> has tricky behaviours that are expected to change to become less
932tricky in the future. Do not rely upon its current (mis)implementation.
933Before Perl 5.18, C<given> also had tricky behaviours that you should still
934beware of if your code must run on older versions of Perl.
935
936Here is a longer example of C<given>:
937
938 use feature ":5.10";
939 given ($foo) {
940 when (undef) {
941 say '$foo is undefined';
942 }
943 when ("foo") {
944 say '$foo is the string "foo"';
945 }
946 when ([1,3,5,7,9]) {
947 say '$foo is an odd digit';
948 continue; # Fall through
949 }
950 when ($_ < 100) {
951 say '$foo is numerically less than 100';
952 }
953 when (\&complicated_check) {
954 say 'a complicated check for $foo is true';
955 }
956 default {
957 die q(I don't know what to do with $foo);
958 }
959 }
960
961Before Perl 5.18, C<given(EXPR)> assigned the value of I<EXPR> to
962merely a lexically scoped I<B<copy>> (!) of C<$_>, not a dynamically
963scoped alias the way C<foreach> does. That made it similar to
964
965 do { my $_ = EXPR; ... }
966
967except that the block was automatically broken out of by a successful
968C<when> or an explicit C<break>. Because it was only a copy, and because
969it was only lexically scoped, not dynamically scoped, you could not do the
970things with it that you are used to in a C<foreach> loop. In particular,
971it did not work for arbitrary function calls if those functions might try
972to access $_. Best stick to C<foreach> for that.
973
974Most of the power comes from the implicit smartmatching that can
975sometimes apply. Most of the time, C<when(EXPR)> is treated as an
976implicit smartmatch of C<$_>, that is, C<$_ ~~ EXPR>. (See
977L<perlop/"Smartmatch Operator"> for more information on smartmatching.)
978But when I<EXPR> is one of the 10 exceptional cases (or things like them)
979listed below, it is used directly as a boolean.
980
981=over 4
982
983=item Z<>1.
984
985A user-defined subroutine call or a method invocation.
986
987=item Z<>2.
988
989A regular expression match in the form of C</REGEX/>, C<$foo =~ /REGEX/>,
990or C<$foo =~ EXPR>. Also, a negated regular expression match in
991the form C<!/REGEX/>, C<$foo !~ /REGEX/>, or C<$foo !~ EXPR>.
992
993=item Z<>3.
994
995A smart match that uses an explicit C<~~> operator, such as C<EXPR ~~ EXPR>.
996
997B<NOTE:> You will often have to use C<$c ~~ $_> because the default case
dabde021 998uses C<$_ ~~ $c> , which is frequently the opposite of what you want.
7896dde7
Z
999
1000=item Z<>4.
1001
1002A boolean comparison operator such as C<$_ E<lt> 10> or C<$x eq "abc">. The
1003relational operators that this applies to are the six numeric comparisons
1004(C<< < >>, C<< > >>, C<< <= >>, C<< >= >>, C<< == >>, and C<< != >>), and
1005the six string comparisons (C<lt>, C<gt>, C<le>, C<ge>, C<eq>, and C<ne>).
1006
1007=item Z<>5.
1008
1009At least the three builtin functions C<defined(...)>, C<exists(...)>, and
1010C<eof(...)>. We might someday add more of these later if we think of them.
1011
1012=item Z<>6.
1013
1014A negated expression, whether C<!(EXPR)> or C<not(EXPR)>, or a logical
1015exclusive-or, C<(EXPR1) xor (EXPR2)>. The bitwise versions (C<~> and C<^>)
1016are not included.
1017
1018=item Z<>7.
1019
1020A filetest operator, with exactly 4 exceptions: C<-s>, C<-M>, C<-A>, and
1021C<-C>, as these return numerical values, not boolean ones. The C<-z>
1022filetest operator is not included in the exception list.
1023
1024=item Z<>8.
1025
1026The C<..> and C<...> flip-flop operators. Note that the C<...> flip-flop
1027operator is completely different from the C<...> elliptical statement
1028just described.
1029
1030=back
1031
1032In those 8 cases above, the value of EXPR is used directly as a boolean, so
1033no smartmatching is done. You may think of C<when> as a smartsmartmatch.
1034
1035Furthermore, Perl inspects the operands of logical operators to
1036decide whether to use smartmatching for each one by applying the
1037above test to the operands:
1038
1039=over 4
1040
1041=item Z<>9.
1042
1043If EXPR is C<EXPR1 && EXPR2> or C<EXPR1 and EXPR2>, the test is applied
1044I<recursively> to both EXPR1 and EXPR2.
1045Only if I<both> operands also pass the
1046test, I<recursively>, will the expression be treated as boolean. Otherwise,
1047smartmatching is used.
1048
1049=item Z<>10.
1050
1051If EXPR is C<EXPR1 || EXPR2>, C<EXPR1 // EXPR2>, or C<EXPR1 or EXPR2>, the
1052test is applied I<recursively> to EXPR1 only (which might itself be a
1053higher-precedence AND operator, for example, and thus subject to the
1054previous rule), not to EXPR2. If EXPR1 is to use smartmatching, then EXPR2
1055also does so, no matter what EXPR2 contains. But if EXPR2 does not get to
1056use smartmatching, then the second argument will not be either. This is
1057quite different from the C<&&> case just described, so be careful.
1058
1059=back
1060
1061These rules are complicated, but the goal is for them to do what you want
1062(even if you don't quite understand why they are doing it). For example:
1063
1064 when (/^\d+$/ && $_ < 75) { ... }
1065
1066will be treated as a boolean match because the rules say both
1067a regex match and an explicit test on C<$_> will be treated
1068as boolean.
1069
1070Also:
1071
1072 when ([qw(foo bar)] && /baz/) { ... }
1073
1074will use smartmatching because only I<one> of the operands is a boolean:
1075the other uses smartmatching, and that wins.
1076
1077Further:
1078
1079 when ([qw(foo bar)] || /^baz/) { ... }
1080
1081will use smart matching (only the first operand is considered), whereas
1082
1083 when (/^baz/ || [qw(foo bar)]) { ... }
1084
1085will test only the regex, which causes both operands to be
1086treated as boolean. Watch out for this one, then, because an
1087arrayref is always a true value, which makes it effectively
1088redundant. Not a good idea.
1089
1090Tautologous boolean operators are still going to be optimized
1091away. Don't be tempted to write
1092
1093 when ("foo" or "bar") { ... }
1094
1095This will optimize down to C<"foo">, so C<"bar"> will never be considered (even
1096though the rules say to use a smartmatch
1097on C<"foo">). For an alternation like
1098this, an array ref will work, because this will instigate smartmatching:
1099
1100 when ([qw(foo bar)] { ... }
1101
1102This is somewhat equivalent to the C-style switch statement's fallthrough
1103functionality (not to be confused with I<Perl's> fallthrough
1104functionality--see below), wherein the same block is used for several
1105C<case> statements.
1106
1107Another useful shortcut is that, if you use a literal array or hash as the
1108argument to C<given>, it is turned into a reference. So C<given(@foo)> is
1109the same as C<given(\@foo)>, for example.
1110
1111C<default> behaves exactly like C<when(1 == 1)>, which is
1112to say that it always matches.
1113
1114=head3 Breaking out
1115
1116You can use the C<break> keyword to break out of the enclosing
1117C<given> block. Every C<when> block is implicitly ended with
1118a C<break>.
1119
1120=head3 Fall-through
1121
1122You can use the C<continue> keyword to fall through from one
1123case to the next immediate C<when> or C<default>:
1124
1125 given($foo) {
1126 when (/x/) { say '$foo contains an x'; continue }
1127 when (/y/) { say '$foo contains a y' }
1128 default { say '$foo does not contain a y' }
1129 }
1130
1131=head3 Return value
1132
1133When a C<given> statement is also a valid expression (for example,
1134when it's the last statement of a block), it evaluates to:
1135
1136=over 4
1137
1138=item *
1139
1140An empty list as soon as an explicit C<break> is encountered.
1141
1142=item *
1143
1144The value of the last evaluated expression of the successful
1145C<when>/C<default> clause, if there happens to be one.
1146
1147=item *
1148
1149The value of the last evaluated expression of the C<given> block if no
1150condition is true.
1151
1152=back
1153
1154In both last cases, the last expression is evaluated in the context that
1155was applied to the C<given> block.
1156
1157Note that, unlike C<if> and C<unless>, failed C<when> statements always
1158evaluate to an empty list.
1159
1160 my $price = do {
1161 given ($item) {
1162 when (["pear", "apple"]) { 1 }
1163 break when "vote"; # My vote cannot be bought
1164 1e10 when /Mona Lisa/;
1165 "unknown";
1166 }
1167 };
1168
1169Currently, C<given> blocks can't always
1170be used as proper expressions. This
1171may be addressed in a future version of Perl.
1172
1173=head3 Switching in a loop
1174
1175Instead of using C<given()>, you can use a C<foreach()> loop.
1176For example, here's one way to count how many times a particular
1177string occurs in an array:
1178
1179 use v5.10.1;
1180 my $count = 0;
1181 for (@array) {
1182 when ("foo") { ++$count }
1183 }
1184 print "\@array contains $count copies of 'foo'\n";
1185
1186Or in a more recent version:
1187
1188 use v5.14;
1189 my $count = 0;
1190 for (@array) {
1191 ++$count when "foo";
1192 }
1193 print "\@array contains $count copies of 'foo'\n";
1194
1195At the end of all C<when> blocks, there is an implicit C<next>.
1196You can override that with an explicit C<last> if you're
1197interested in only the first match alone.
1198
1199This doesn't work if you explicitly specify a loop variable, as
1200in C<for $item (@array)>. You have to use the default variable C<$_>.
1201
17b35041 1202=head3 Differences from Raku
7896dde7
Z
1203
1204The Perl 5 smartmatch and C<given>/C<when> constructs are not compatible
17b35041 1205with their Raku analogues. The most visible difference and least
7896dde7
Z
1206important difference is that, in Perl 5, parentheses are required around
1207the argument to C<given()> and C<when()> (except when this last one is used
17b35041 1208as a statement modifier). Parentheses in Raku are always optional in a
7896dde7
Z
1209control construct such as C<if()>, C<while()>, or C<when()>; they can't be
1210made optional in Perl 5 without a great deal of potential confusion,
1211because Perl 5 would parse the expression
1212
1213 given $foo {
1214 ...
1215 }
1216
1217as though the argument to C<given> were an element of the hash
1218C<%foo>, interpreting the braces as hash-element syntax.
1219
1220However, their are many, many other differences. For example,
1221this works in Perl 5:
1222
1223 use v5.12;
1224 my @primary = ("red", "blue", "green");
1225
1226 if (@primary ~~ "red") {
1227 say "primary smartmatches red";
1228 }
1229
1230 if ("red" ~~ @primary) {
1231 say "red smartmatches primary";
1232 }
1233
1234 say "that's all, folks!";
1235
17b35041 1236But it doesn't work at all in Raku. Instead, you should
7896dde7
Z
1237use the (parallelizable) C<any> operator:
1238
1239 if any(@primary) eq "red" {
1240 say "primary smartmatches red";
1241 }
1242
1243 if "red" eq any(@primary) {
1244 say "red smartmatches primary";
1245 }
1246
1247The table of smartmatches in L<perlop/"Smartmatch Operator"> is not
17b35041
MB
1248identical to that proposed by the Raku specification, mainly due to
1249differences between Raku's and Perl 5's data models, but also because
1250the Raku spec has changed since Perl 5 rushed into early adoption.
7896dde7 1251
17b35041 1252In Raku, C<when()> will always do an implicit smartmatch with its
7896dde7
Z
1253argument, while in Perl 5 it is convenient (albeit potentially confusing) to
1254suppress this implicit smartmatch in various rather loosely-defined
1255situations, as roughly outlined above. (The difference is largely because
1256Perl 5 does not have, even internally, a boolean type.)
1257
774d564b 1258=cut