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