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