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