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