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.
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.
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.
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.
32 X<declaration> X<undef> X<undefined> X<uninitialized>
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,
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:
54 are also always exempt from such warnings.
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.
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>
71 $me = myname $0 or die "can't get myname";
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
83 $me = myname $0 || die "can't get myname";
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
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.
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.
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
106 =head2 Simple Statements
107 X<statement> X<semicolon> X<expression> X<;>
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.
119 =head2 Statement Modifiers
120 X<statement modifier> X<modifier> X<if> X<unless> X<while>
121 X<until> X<when> X<foreach> X<for>
123 Any simple statement may optionally be followed by a I<SINGLE> modifier,
124 just before the terminating semicolon (or block ending). The possible
135 The C<EXPR> following the modifier is referred to as the "condition".
136 Its truth or falsehood determines how the modifier will behave.
138 C<if> executes the statement once I<if> and only if the condition is
139 true. C<unless> is the opposite, it executes the statement I<unless>
140 the condition is true (that is, if the condition is false).
142 print "Basset hounds got long ears" if length $ear >= 10;
143 go_outside() and play() unless $is_raining;
145 The C<for(each)> modifier is an iterator: it executes the statement once
146 for each item in the LIST (with C<$_> aliased to each item in turn).
148 print "Hello $_!\n" for qw(world Dolly nurse);
150 C<while> repeats the statement I<while> the condition is true.
151 Postfix C<while> has the same magic treatment of some kinds of condition
152 that prefix C<while> has.
153 C<until> does the opposite, it repeats the statement I<until> the
154 condition is true (or while the condition is false):
156 # Both of these count from 0 to 10.
157 print $i++ while $i <= 10;
158 print $j++ until $j > 10;
160 The C<while> and C<until> modifiers have the usual "C<while> loop"
161 semantics (conditional evaluated first), except when applied to a
162 C<do>-BLOCK (or to the Perl4 C<do>-SUBROUTINE statement), in
163 which case the block executes once before the conditional is
166 This is so that you can write loops like:
171 } until !defined($line) || $line eq ".\n"
173 See L<perlfunc/do>. Note also that the loop control statements described
174 later will I<NOT> work in this construct, because modifiers don't take
175 loop labels. Sorry. You can always put another block inside of it
176 (for C<next>/C<redo>) or around it (for C<last>) to do that sort of thing.
177 X<next> X<last> X<redo>
179 For C<next> or C<redo>, just double the braces:
186 For C<last>, you have to be more elaborate and put braces around it:
196 If you need both C<next> and C<last>, you have to do both and also use a
202 last LOOP if $x == $y**2;
207 B<NOTE:> The behaviour of a C<my>, C<state>, or
208 C<our> modified with a statement modifier conditional
209 or loop construct (for example, C<my $x if ...>) is
210 B<undefined>. The value of the C<my> variable may be C<undef>, any
211 previously assigned value, or possibly anything else. Don't rely on
212 it. Future versions of perl might do something different from the
213 version of perl you try it out on. Here be dragons.
216 The C<when> modifier is an experimental feature that first appeared in Perl
217 5.14. To use it, you should include a C<use v5.14> declaration.
218 (Technically, it requires only the C<switch> feature, but that aspect of it
219 was not available before 5.14.) Operative only from within a C<foreach>
220 loop or a C<given> block, it executes the statement only if the smartmatch
221 C<< $_ ~~ I<EXPR> >> is true. If the statement executes, it is followed by
222 a C<next> from inside a C<foreach> and C<break> from inside a C<given>.
224 Under the current implementation, the C<foreach> loop can be
225 anywhere within the C<when> modifier's dynamic scope, but must be
226 within the C<given> block's lexical scope. This restriction may
227 be relaxed in a future release. See L</"Switch Statements"> below.
229 =head2 Compound Statements
230 X<statement, compound> X<block> X<bracket, curly> X<curly bracket> X<brace>
231 X<{> X<}> X<if> X<unless> X<given> X<while> X<until> X<foreach> X<for> X<continue>
233 In Perl, a sequence of statements that defines a scope is called a block.
234 Sometimes a block is delimited by the file containing it (in the case
235 of a required file, or the program as a whole), and sometimes a block
236 is delimited by the extent of a string (in the case of an eval).
238 But generally, a block is delimited by curly brackets, also known as
239 braces. We will call this syntactic construct a BLOCK. Because enclosing
240 braces are also the syntax for hash reference constructor expressions
241 (see L<perlref>), you may occasionally need to disambiguate by placing a
242 C<;> immediately after an opening brace so that Perl realises the brace
243 is the start of a block. You will more frequently need to disambiguate
244 the other way, by placing a C<+> immediately before an opening brace to
245 force it to be interpreted as a hash reference constructor expression.
246 It is considered good style to use these disambiguating mechanisms
247 liberally, not only when Perl would otherwise guess incorrectly.
249 The following compound statements may be used to control flow:
252 if (EXPR) BLOCK else BLOCK
253 if (EXPR) BLOCK elsif (EXPR) BLOCK ...
254 if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
257 unless (EXPR) BLOCK else BLOCK
258 unless (EXPR) BLOCK elsif (EXPR) BLOCK ...
259 unless (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
263 LABEL while (EXPR) BLOCK
264 LABEL while (EXPR) BLOCK continue BLOCK
266 LABEL until (EXPR) BLOCK
267 LABEL until (EXPR) BLOCK continue BLOCK
269 LABEL for (EXPR; EXPR; EXPR) BLOCK
270 LABEL for VAR (LIST) BLOCK
271 LABEL for VAR (LIST) BLOCK continue BLOCK
273 LABEL foreach (EXPR; EXPR; EXPR) BLOCK
274 LABEL foreach VAR (LIST) BLOCK
275 LABEL foreach VAR (LIST) BLOCK continue BLOCK
278 LABEL BLOCK continue BLOCK
282 The experimental C<given> statement is I<not automatically enabled>; see
283 L</"Switch Statements"> below for how to do so, and the attendant caveats.
285 Unlike in C and Pascal, in Perl these are all defined in terms of BLOCKs,
286 not statements. This means that the curly brackets are I<required>--no
287 dangling statements allowed. If you want to write conditionals without
288 curly brackets, there are several other ways to do it. The following
289 all do the same thing:
291 if (!open(FOO)) { die "Can't open $FOO: $!" }
292 die "Can't open $FOO: $!" unless open(FOO);
293 open(FOO) || die "Can't open $FOO: $!";
294 open(FOO) ? () : die "Can't open $FOO: $!";
295 # a bit exotic, that last one
297 The C<if> statement is straightforward. Because BLOCKs are always
298 bounded by curly brackets, there is never any ambiguity about which
299 C<if> an C<else> goes with. If you use C<unless> in place of C<if>,
300 the sense of the test is reversed. Like C<if>, C<unless> can be followed
301 by C<else>. C<unless> can even be followed by one or more C<elsif>
302 statements, though you may want to think twice before using that particular
303 language construct, as everyone reading your code will have to think at least
304 twice before they can understand what's going on.
306 The C<while> statement executes the block as long as the expression is
308 The C<until> statement executes the block as long as the expression is
310 The LABEL is optional, and if present, consists of an identifier followed
311 by a colon. The LABEL identifies the loop for the loop control
312 statements C<next>, C<last>, and C<redo>.
313 If the LABEL is omitted, the loop control statement
314 refers to the innermost enclosing loop. This may include dynamically
315 looking back your call-stack at run time to find the LABEL. Such
316 desperate behavior triggers a warning if you use the C<use warnings>
317 pragma or the B<-w> flag.
319 If the condition expression of a C<while> statement is based
320 on any of a group of iterative expression types then it gets
321 some magic treatment. The affected iterative expression types
322 are L<C<readline>|perlfunc/readline EXPR>, the L<C<< <FILEHANDLE>
323 >>|perlop/"I/O Operators"> input operator, L<C<readdir>|perlfunc/readdir
324 DIRHANDLE>, L<C<glob>|perlfunc/glob EXPR>, the L<C<< <PATTERN>
325 >>|perlop/"I/O Operators"> globbing operator, and L<C<each>|perlfunc/each
326 HASH>. If the condition expression is one of these expression types, then
327 the value yielded by the iterative operator will be implicitly assigned
328 to C<$_>. If the condition expression is one of these expression types
329 or an explicit assignment of one of them to a scalar, then the condition
330 actually tests for definedness of the expression's value, not for its
333 If there is a C<continue> BLOCK, it is always executed just before the
334 conditional is about to be evaluated again. Thus it can be used to
335 increment a loop variable, even when the loop has been continued via
336 the C<next> statement.
338 When a block is preceded by a compilation phase keyword such as C<BEGIN>,
339 C<END>, C<INIT>, C<CHECK>, or C<UNITCHECK>, then the block will run only
340 during the corresponding phase of execution. See L<perlmod> for more details.
342 Extension modules can also hook into the Perl parser to define new
343 kinds of compound statements. These are introduced by a keyword which
344 the extension recognizes, and the syntax following the keyword is
345 defined entirely by the extension. If you are an implementor, see
346 L<perlapi/PL_keyword_plugin> for the mechanism. If you are using such
347 a module, see the module's documentation for details of the syntax that
351 X<loop control> X<loop, control> X<next> X<last> X<redo> X<continue>
353 The C<next> command starts the next iteration of the loop:
355 LINE: while (<STDIN>) {
356 next LINE if /^#/; # discard comments
360 The C<last> command immediately exits the loop in question. The
361 C<continue> block, if any, is not executed:
363 LINE: while (<STDIN>) {
364 last LINE if /^$/; # exit when done with header
368 The C<redo> command restarts the loop block without evaluating the
369 conditional again. The C<continue> block, if any, is I<not> executed.
370 This command is normally used by programs that want to lie to themselves
371 about what was just input.
373 For example, when processing a file like F</etc/termcap>.
374 If your input lines might end in backslashes to indicate continuation, you
375 want to skip ahead and get the next record.
386 which is Perl shorthand for the more explicitly written version:
388 LINE: while (defined($line = <ARGV>)) {
390 if ($line =~ s/\\$//) {
392 redo LINE unless eof(); # not eof(ARGV)!
397 Note that if there were a C<continue> block on the above code, it would
398 get executed only on lines discarded by the regex (since redo skips the
399 continue block). A continue block is often used to reset line counters
400 or C<m?pat?> one-time matches:
402 # inspired by :1,$g/fred/s//WILMA/
404 m?(fred)? && s//WILMA $1 WILMA/;
405 m?(barney)? && s//BETTY $1 BETTY/;
406 m?(homer)? && s//MARGE $1 MARGE/;
408 print "$ARGV $.: $_";
409 close ARGV if eof; # reset $.
410 reset if eof; # reset ?pat?
413 If the word C<while> is replaced by the word C<until>, the sense of the
414 test is reversed, but the conditional is still tested before the first
417 Loop control statements don't work in an C<if> or C<unless>, since
418 they aren't loops. You can double the braces to make them such, though.
422 next if /barney/; # same effect as "last",
423 # but doesn't document as well
427 This is caused by the fact that a block by itself acts as a loop that
428 executes once, see L</"Basic BLOCKs">.
430 The form C<while/if BLOCK BLOCK>, available in Perl 4, is no longer
431 available. Replace any occurrence of C<if BLOCK> by C<if (do BLOCK)>.
436 Perl's C-style C<for> loop works like the corresponding C<while> loop;
437 that means that this:
439 for ($i = 1; $i < 10; $i++) {
452 There is one minor difference: if variables are declared with C<my>
453 in the initialization section of the C<for>, the lexical scope of
454 those variables is exactly the C<for> loop (the body of the loop
455 and the control sections).
458 As a special case, if the test in the C<for> loop (or the corresponding
459 C<while> loop) is empty, it is treated as true. That is, both
471 are treated as infinite loops.
473 Besides the normal array index looping, C<for> can lend itself
474 to many other interesting applications. Here's one that avoids the
475 problem you get into if you explicitly test for end-of-file on
476 an interactive file descriptor causing your program to appear to
478 X<eof> X<end-of-file> X<end of file>
480 $on_a_tty = -t STDIN && -t STDOUT;
481 sub prompt { print "yes? " if $on_a_tty }
482 for ( prompt(); <STDIN>; prompt() ) {
486 The condition expression of a C<for> loop gets the same magic treatment of
487 C<readline> et al that the condition expression of a C<while> loop gets.
492 The C<foreach> loop iterates over a normal list value and sets the scalar
493 variable VAR to be each element of the list in turn. If the variable
494 is preceded with the keyword C<my>, then it is lexically scoped, and
495 is therefore visible only within the loop. Otherwise, the variable is
496 implicitly local to the loop and regains its former value upon exiting
497 the loop. If the variable was previously declared with C<my>, it uses
498 that variable instead of the global one, but it's still localized to
499 the loop. This implicit localization occurs I<only> in a C<foreach>
503 The C<foreach> keyword is actually a synonym for the C<for> keyword, so
504 you can use either. If VAR is omitted, C<$_> is set to each value.
507 If any element of LIST is an lvalue, you can modify it by modifying
508 VAR inside the loop. Conversely, if any element of LIST is NOT an
509 lvalue, any attempt to modify that element will fail. In other words,
510 the C<foreach> loop index variable is an implicit alias for each item
511 in the list that you're looping over.
514 If any part of LIST is an array, C<foreach> will get very confused if
515 you add or remove elements within the loop body, for example with
516 C<splice>. So don't do that.
519 C<foreach> probably won't do what you expect if VAR is a tied or other
520 special variable. Don't do that either.
522 As of Perl 5.22, there is an experimental variant of this loop that accepts
523 a variable preceded by a backslash for VAR, in which case the items in the
524 LIST must be references. The backslashed variable will become an alias
525 to each referenced item in the LIST, which must be of the correct type.
526 The variable needn't be a scalar in this case, and the backslash may be
527 followed by C<my>. To use this form, you must enable the C<refaliasing>
528 feature via C<use feature>. (See L<feature>. See also L<perlref/Assigning
533 for (@ary) { s/foo/bar/ }
535 for my $elem (@elements) {
539 for $count (reverse(1..10), "BOOM") {
544 for (1..15) { print "Merry Christmas\n"; }
546 foreach $item (split(/:[\\\n:]*/, $ENV{TERMCAP})) {
547 print "Item: $item\n";
550 use feature "refaliasing";
551 no warnings "experimental::refaliasing";
552 foreach \my %hash (@array_of_hash_references) {
553 # do something which each %hash
556 Here's how a C programmer might code up a particular algorithm in Perl:
558 for (my $i = 0; $i < @ary1; $i++) {
559 for (my $j = 0; $j < @ary2; $j++) {
560 if ($ary1[$i] > $ary2[$j]) {
561 last; # can't go to outer :-(
563 $ary1[$i] += $ary2[$j];
565 # this is where that last takes me
568 Whereas here's how a Perl programmer more comfortable with the idiom might
571 OUTER: for my $wid (@ary1) {
572 INNER: for my $jet (@ary2) {
573 next OUTER if $wid > $jet;
578 See how much easier this is? It's cleaner, safer, and faster. It's
579 cleaner because it's less noisy. It's safer because if code gets added
580 between the inner and outer loops later on, the new code won't be
581 accidentally executed. The C<next> explicitly iterates the other loop
582 rather than merely terminating the inner one. And it's faster because
583 Perl executes a C<foreach> statement more rapidly than it would the
584 equivalent C-style C<for> loop.
586 Perceptive Perl hackers may have noticed that a C<for> loop has a return
587 value, and that this value can be captured by wrapping the loop in a C<do>
588 block. The reward for this discovery is this cautionary advice: The
589 return value of a C<for> loop is unspecified and may change without notice.
595 A BLOCK by itself (labeled or not) is semantically equivalent to a
596 loop that executes once. Thus you can use any of the loop control
597 statements in it to leave or restart the block. (Note that this is
598 I<NOT> true in C<eval{}>, C<sub{}>, or contrary to popular belief
599 C<do{}> blocks, which do I<NOT> count as loops.) The C<continue>
602 The BLOCK construct can be used to emulate case structures.
605 if (/^abc/) { $abc = 1; last SWITCH; }
606 if (/^def/) { $def = 1; last SWITCH; }
607 if (/^xyz/) { $xyz = 1; last SWITCH; }
611 You'll also find that C<foreach> loop used to create a topicalizer
616 if (/^abc/) { $abc = 1; last SWITCH; }
617 if (/^def/) { $def = 1; last SWITCH; }
618 if (/^xyz/) { $xyz = 1; last SWITCH; }
622 Such constructs are quite frequently used, both because older versions of
623 Perl had no official C<switch> statement, and also because the new version
624 described immediately below remains experimental and can sometimes be confusing.
626 =head2 Switch Statements
628 X<switch> X<case> X<given> X<when> X<default>
630 Starting from Perl 5.10.1 (well, 5.10.0, but it didn't work
633 use feature "switch";
635 to enable an experimental switch feature. This is loosely based on an
636 old version of a Perl 6 proposal, but it no longer resembles the Perl 6
637 construct. You also get the switch feature whenever you declare that your
638 code prefers to run under a version of Perl that is 5.10 or later. For
643 Under the "switch" feature, Perl gains the experimental keywords
644 C<given>, C<when>, C<default>, C<continue>, and C<break>.
645 Starting from Perl 5.16, one can prefix the switch
646 keywords with C<CORE::> to access the feature without a C<use feature>
647 statement. The keywords C<given> and
648 C<when> are analogous to C<switch> and
649 C<case> in other languages -- though C<continue> is not -- so the code
650 in the previous section could be rewritten as
654 when (/^abc/) { $abc = 1 }
655 when (/^def/) { $def = 1 }
656 when (/^xyz/) { $xyz = 1 }
657 default { $nothing = 1 }
660 The C<foreach> is the non-experimental way to set a topicalizer.
661 If you wish to use the highly experimental C<given>, that could be
666 when (/^abc/) { $abc = 1 }
667 when (/^def/) { $def = 1 }
668 when (/^xyz/) { $xyz = 1 }
669 default { $nothing = 1 }
672 As of 5.14, that can also be written this way:
676 $abc = 1 when /^abc/;
677 $def = 1 when /^def/;
678 $xyz = 1 when /^xyz/;
679 default { $nothing = 1 }
682 Or if you don't care to play it safe, like this:
686 $abc = 1 when /^abc/;
687 $def = 1 when /^def/;
688 $xyz = 1 when /^xyz/;
689 default { $nothing = 1 }
692 The arguments to C<given> and C<when> are in scalar context,
693 and C<given> assigns the C<$_> variable its topic value.
695 Exactly what the I<EXPR> argument to C<when> does is hard to describe
696 precisely, but in general, it tries to guess what you want done. Sometimes
697 it is interpreted as C<< $_ ~~ I<EXPR> >>, and sometimes it is not. It
698 also behaves differently when lexically enclosed by a C<given> block than
699 it does when dynamically enclosed by a C<foreach> loop. The rules are far
700 too difficult to understand to be described here. See L</"Experimental Details
701 on given and when"> later on.
703 Due to an unfortunate bug in how C<given> was implemented between Perl 5.10
704 and 5.16, under those implementations the version of C<$_> governed by
705 C<given> is merely a lexically scoped copy of the original, not a
706 dynamically scoped alias to the original, as it would be if it were a
707 C<foreach> or under both the original and the current Perl 6 language
708 specification. This bug was fixed in Perl 5.18 (and lexicalized C<$_> itself
709 was removed in Perl 5.24).
711 If your code still needs to run on older versions,
712 stick to C<foreach> for your topicalizer and
713 you will be less unhappy.
718 Although not for the faint of heart, Perl does support a C<goto>
719 statement. There are three forms: C<goto>-LABEL, C<goto>-EXPR, and
720 C<goto>-&NAME. A loop's LABEL is not actually a valid target for
721 a C<goto>; it's just the name of the loop.
723 The C<goto>-LABEL form finds the statement labeled with LABEL and resumes
724 execution there. It may not be used to go into any construct that
725 requires initialization, such as a subroutine or a C<foreach> loop. It
726 also can't be used to go into a construct that is optimized away. It
727 can be used to go almost anywhere else within the dynamic scope,
728 including out of subroutines, but it's usually better to use some other
729 construct such as C<last> or C<die>. The author of Perl has never felt the
730 need to use this form of C<goto> (in Perl, that is--C is another matter).
732 The C<goto>-EXPR form expects a label name, whose scope will be resolved
733 dynamically. This allows for computed C<goto>s per FORTRAN, but isn't
734 necessarily recommended if you're optimizing for maintainability:
736 goto(("FOO", "BAR", "GLARCH")[$i]);
738 The C<goto>-&NAME form is highly magical, and substitutes a call to the
739 named subroutine for the currently running subroutine. This is used by
740 C<AUTOLOAD()> subroutines that wish to load another subroutine and then
741 pretend that the other subroutine had been called in the first place
742 (except that any modifications to C<@_> in the current subroutine are
743 propagated to the other subroutine.) After the C<goto>, not even C<caller()>
744 will be able to tell that this routine was called first.
746 In almost all cases like this, it's usually a far, far better idea to use the
747 structured control flow mechanisms of C<next>, C<last>, or C<redo> instead of
748 resorting to a C<goto>. For certain applications, the catch and throw pair of
749 C<eval{}> and die() for exception processing can also be a prudent approach.
751 =head2 The Ellipsis Statement
755 X<elliptical statement>
756 X<unimplemented statement>
757 X<unimplemented operator>
759 X<yada-yada operator>
762 X<triple-dot operator>
764 Beginning in Perl 5.12, Perl accepts an ellipsis, "C<...>", as a
765 placeholder for code that you haven't implemented yet.
766 When Perl 5.12 or later encounters an ellipsis statement, it parses this
767 without error, but if and when you should actually try to execute it, Perl
768 throws an exception with the text C<Unimplemented>:
771 sub unimplemented { ... }
772 eval { unimplemented() };
773 if ($@ =~ /^Unimplemented at /) {
774 say "I found an ellipsis!";
777 You can only use the elliptical statement to stand in for a complete
778 statement. Syntactically, "C<...;>" is a complete statement, but,
779 as with other kinds of semicolon-terminated statement, the semicolon
780 may be omitted if "C<...>" appears immediately before a closing brace.
781 These examples show how the ellipsis works:
799 The elliptical statement cannot stand in for an expression that
800 is part of a larger statement.
801 These examples of attempts to use an ellipsis are syntax errors:
806 open(my $fh, ">", "/dev/passwd") or ...;
807 if ($condition && ... ) { say "Howdy" };
809 say "Cromulent" if ...;
812 There are some cases where Perl can't immediately tell the difference
813 between an expression and a statement. For instance, the syntax for a
814 block and an anonymous hash reference constructor look the same unless
815 there's something in the braces to give Perl a hint. The ellipsis is a
816 syntax error if Perl doesn't guess that the C<{ ... }> is a block.
817 Inside your block, you can use a C<;> before the ellipsis to denote that the
818 C<{ ... }> is a block and not a hash reference constructor.
820 Note: Some folks colloquially refer to this bit of punctuation as a
821 "yada-yada" or "triple-dot", but its true name
822 is actually an ellipsis.
824 =head2 PODs: Embedded Documentation
825 X<POD> X<documentation>
827 Perl has a mechanism for intermixing documentation with source code.
828 While it's expecting the beginning of a new statement, if the compiler
829 encounters a line that begins with an equal sign and a word, like this
831 =head1 Here There Be Pods!
833 Then that text and all remaining text up through and including a line
834 beginning with C<=cut> will be ignored. The format of the intervening
835 text is described in L<perlpod>.
837 This allows you to intermix your source code
838 and your documentation text freely, as in
842 The snazzle() function will behave in the most spectacular
843 form that you can possibly imagine, not even excepting
844 cybernetic pyrotechnics.
846 =cut back to the compiler, nuff of this pod stuff!
853 Note that pod translators should look at only paragraphs beginning
854 with a pod directive (it makes parsing easier), whereas the compiler
855 actually knows to look for pod escapes even in the middle of a
856 paragraph. This means that the following secret stuff will be
857 ignored by both the compiler and the translators.
861 warn "Neither POD nor CODE!?"
865 You probably shouldn't rely upon the C<warn()> being podded out forever.
866 Not all pod translators are well-behaved in this regard, and perhaps
867 the compiler will become pickier.
869 One may also use pod directives to quickly comment out a section
872 =head2 Plain Old Comments (Not!)
873 X<comment> X<line> X<#> X<preprocessor> X<eval>
875 Perl can process line directives, much like the C preprocessor. Using
876 this, one can control Perl's idea of filenames and line numbers in
877 error or warning messages (especially for strings that are processed
878 with C<eval()>). The syntax for this mechanism is almost the same as for
879 most C preprocessors: it matches the regular expression
881 # example: '# line 42 "new_filename.plx"'
884 (?:\s("?)([^"]+)\g2)? \s*
887 with C<$1> being the line number for the next line, and C<$3> being
888 the optional filename (specified with or without quotes). Note that
889 no whitespace may precede the C<< # >>, unlike modern C preprocessors.
891 There is a fairly obvious gotcha included with the line directive:
892 Debuggers and profilers will only show the last source line to appear
893 at a particular line number in a given file. Care should be taken not
894 to cause line number collisions in code you'd like to debug later.
896 Here are some examples that you should be able to type into your command
901 # the '#' on the previous line must be the first char on line
904 foo at bzzzt line 201.
908 eval qq[\n#line 2001 ""\ndie 'foo']; print $@;
913 eval qq[\n#line 200 "foo bar"\ndie 'foo']; print $@;
915 foo at foo bar line 200.
919 eval "\n#line " . __LINE__ . ' "' . __FILE__ ."\"\ndie 'foo'";
922 foo at goop line 345.
924 =head2 Experimental Details on given and when
926 As previously mentioned, the "switch" feature is considered highly
927 experimental; it is subject to change with little notice. In particular,
928 C<when> has tricky behaviours that are expected to change to become less
929 tricky in the future. Do not rely upon its current (mis)implementation.
930 Before Perl 5.18, C<given> also had tricky behaviours that you should still
931 beware of if your code must run on older versions of Perl.
933 Here is a longer example of C<given>:
938 say '$foo is undefined';
941 say '$foo is the string "foo"';
944 say '$foo is an odd digit';
945 continue; # Fall through
948 say '$foo is numerically less than 100';
950 when (\&complicated_check) {
951 say 'a complicated check for $foo is true';
954 die q(I don't know what to do with $foo);
958 Before Perl 5.18, C<given(EXPR)> assigned the value of I<EXPR> to
959 merely a lexically scoped I<B<copy>> (!) of C<$_>, not a dynamically
960 scoped alias the way C<foreach> does. That made it similar to
962 do { my $_ = EXPR; ... }
964 except that the block was automatically broken out of by a successful
965 C<when> or an explicit C<break>. Because it was only a copy, and because
966 it was only lexically scoped, not dynamically scoped, you could not do the
967 things with it that you are used to in a C<foreach> loop. In particular,
968 it did not work for arbitrary function calls if those functions might try
969 to access $_. Best stick to C<foreach> for that.
971 Most of the power comes from the implicit smartmatching that can
972 sometimes apply. Most of the time, C<when(EXPR)> is treated as an
973 implicit smartmatch of C<$_>, that is, C<$_ ~~ EXPR>. (See
974 L<perlop/"Smartmatch Operator"> for more information on smartmatching.)
975 But when I<EXPR> is one of the 10 exceptional cases (or things like them)
976 listed below, it is used directly as a boolean.
982 A user-defined subroutine call or a method invocation.
986 A regular expression match in the form of C</REGEX/>, C<$foo =~ /REGEX/>,
987 or C<$foo =~ EXPR>. Also, a negated regular expression match in
988 the form C<!/REGEX/>, C<$foo !~ /REGEX/>, or C<$foo !~ EXPR>.
992 A smart match that uses an explicit C<~~> operator, such as C<EXPR ~~ EXPR>.
994 B<NOTE:> You will often have to use C<$c ~~ $_> because the default case
995 uses C<$_ ~~ $c> , which is frequently the opposite of what you want.
999 A boolean comparison operator such as C<$_ E<lt> 10> or C<$x eq "abc">. The
1000 relational operators that this applies to are the six numeric comparisons
1001 (C<< < >>, C<< > >>, C<< <= >>, C<< >= >>, C<< == >>, and C<< != >>), and
1002 the six string comparisons (C<lt>, C<gt>, C<le>, C<ge>, C<eq>, and C<ne>).
1006 At least the three builtin functions C<defined(...)>, C<exists(...)>, and
1007 C<eof(...)>. We might someday add more of these later if we think of them.
1011 A negated expression, whether C<!(EXPR)> or C<not(EXPR)>, or a logical
1012 exclusive-or, C<(EXPR1) xor (EXPR2)>. The bitwise versions (C<~> and C<^>)
1017 A filetest operator, with exactly 4 exceptions: C<-s>, C<-M>, C<-A>, and
1018 C<-C>, as these return numerical values, not boolean ones. The C<-z>
1019 filetest operator is not included in the exception list.
1023 The C<..> and C<...> flip-flop operators. Note that the C<...> flip-flop
1024 operator is completely different from the C<...> elliptical statement
1029 In those 8 cases above, the value of EXPR is used directly as a boolean, so
1030 no smartmatching is done. You may think of C<when> as a smartsmartmatch.
1032 Furthermore, Perl inspects the operands of logical operators to
1033 decide whether to use smartmatching for each one by applying the
1034 above test to the operands:
1040 If EXPR is C<EXPR1 && EXPR2> or C<EXPR1 and EXPR2>, the test is applied
1041 I<recursively> to both EXPR1 and EXPR2.
1042 Only if I<both> operands also pass the
1043 test, I<recursively>, will the expression be treated as boolean. Otherwise,
1044 smartmatching is used.
1048 If EXPR is C<EXPR1 || EXPR2>, C<EXPR1 // EXPR2>, or C<EXPR1 or EXPR2>, the
1049 test is applied I<recursively> to EXPR1 only (which might itself be a
1050 higher-precedence AND operator, for example, and thus subject to the
1051 previous rule), not to EXPR2. If EXPR1 is to use smartmatching, then EXPR2
1052 also does so, no matter what EXPR2 contains. But if EXPR2 does not get to
1053 use smartmatching, then the second argument will not be either. This is
1054 quite different from the C<&&> case just described, so be careful.
1058 These rules are complicated, but the goal is for them to do what you want
1059 (even if you don't quite understand why they are doing it). For example:
1061 when (/^\d+$/ && $_ < 75) { ... }
1063 will be treated as a boolean match because the rules say both
1064 a regex match and an explicit test on C<$_> will be treated
1069 when ([qw(foo bar)] && /baz/) { ... }
1071 will use smartmatching because only I<one> of the operands is a boolean:
1072 the other uses smartmatching, and that wins.
1076 when ([qw(foo bar)] || /^baz/) { ... }
1078 will use smart matching (only the first operand is considered), whereas
1080 when (/^baz/ || [qw(foo bar)]) { ... }
1082 will test only the regex, which causes both operands to be
1083 treated as boolean. Watch out for this one, then, because an
1084 arrayref is always a true value, which makes it effectively
1085 redundant. Not a good idea.
1087 Tautologous boolean operators are still going to be optimized
1088 away. Don't be tempted to write
1090 when ("foo" or "bar") { ... }
1092 This will optimize down to C<"foo">, so C<"bar"> will never be considered (even
1093 though the rules say to use a smartmatch
1094 on C<"foo">). For an alternation like
1095 this, an array ref will work, because this will instigate smartmatching:
1097 when ([qw(foo bar)] { ... }
1099 This is somewhat equivalent to the C-style switch statement's fallthrough
1100 functionality (not to be confused with I<Perl's> fallthrough
1101 functionality--see below), wherein the same block is used for several
1104 Another useful shortcut is that, if you use a literal array or hash as the
1105 argument to C<given>, it is turned into a reference. So C<given(@foo)> is
1106 the same as C<given(\@foo)>, for example.
1108 C<default> behaves exactly like C<when(1 == 1)>, which is
1109 to say that it always matches.
1113 You can use the C<break> keyword to break out of the enclosing
1114 C<given> block. Every C<when> block is implicitly ended with
1119 You can use the C<continue> keyword to fall through from one
1120 case to the next immediate C<when> or C<default>:
1123 when (/x/) { say '$foo contains an x'; continue }
1124 when (/y/) { say '$foo contains a y' }
1125 default { say '$foo does not contain a y' }
1130 When a C<given> statement is also a valid expression (for example,
1131 when it's the last statement of a block), it evaluates to:
1137 An empty list as soon as an explicit C<break> is encountered.
1141 The value of the last evaluated expression of the successful
1142 C<when>/C<default> clause, if there happens to be one.
1146 The value of the last evaluated expression of the C<given> block if no
1151 In both last cases, the last expression is evaluated in the context that
1152 was applied to the C<given> block.
1154 Note that, unlike C<if> and C<unless>, failed C<when> statements always
1155 evaluate to an empty list.
1159 when (["pear", "apple"]) { 1 }
1160 break when "vote"; # My vote cannot be bought
1161 1e10 when /Mona Lisa/;
1166 Currently, C<given> blocks can't always
1167 be used as proper expressions. This
1168 may be addressed in a future version of Perl.
1170 =head3 Switching in a loop
1172 Instead of using C<given()>, you can use a C<foreach()> loop.
1173 For example, here's one way to count how many times a particular
1174 string occurs in an array:
1179 when ("foo") { ++$count }
1181 print "\@array contains $count copies of 'foo'\n";
1183 Or in a more recent version:
1188 ++$count when "foo";
1190 print "\@array contains $count copies of 'foo'\n";
1192 At the end of all C<when> blocks, there is an implicit C<next>.
1193 You can override that with an explicit C<last> if you're
1194 interested in only the first match alone.
1196 This doesn't work if you explicitly specify a loop variable, as
1197 in C<for $item (@array)>. You have to use the default variable C<$_>.
1199 =head3 Differences from Perl 6
1201 The Perl 5 smartmatch and C<given>/C<when> constructs are not compatible
1202 with their Perl 6 analogues. The most visible difference and least
1203 important difference is that, in Perl 5, parentheses are required around
1204 the argument to C<given()> and C<when()> (except when this last one is used
1205 as a statement modifier). Parentheses in Perl 6 are always optional in a
1206 control construct such as C<if()>, C<while()>, or C<when()>; they can't be
1207 made optional in Perl 5 without a great deal of potential confusion,
1208 because Perl 5 would parse the expression
1214 as though the argument to C<given> were an element of the hash
1215 C<%foo>, interpreting the braces as hash-element syntax.
1217 However, their are many, many other differences. For example,
1218 this works in Perl 5:
1221 my @primary = ("red", "blue", "green");
1223 if (@primary ~~ "red") {
1224 say "primary smartmatches red";
1227 if ("red" ~~ @primary) {
1228 say "red smartmatches primary";
1231 say "that's all, folks!";
1233 But it doesn't work at all in Perl 6. Instead, you should
1234 use the (parallelizable) C<any> operator:
1236 if any(@primary) eq "red" {
1237 say "primary smartmatches red";
1240 if "red" eq any(@primary) {
1241 say "red smartmatches primary";
1244 The table of smartmatches in L<perlop/"Smartmatch Operator"> is not
1245 identical to that proposed by the Perl 6 specification, mainly due to
1246 differences between Perl 6's and Perl 5's data models, but also because
1247 the Perl 6 spec has changed since Perl 5 rushed into early adoption.
1249 In Perl 6, C<when()> will always do an implicit smartmatch with its
1250 argument, while in Perl 5 it is convenient (albeit potentially confusing) to
1251 suppress this implicit smartmatch in various rather loosely-defined
1252 situations, as roughly outlined above. (The difference is largely because
1253 Perl 5 does not have, even internally, a boolean type.)