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