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