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