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 is
60 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 As of Perl 5.36, you can iterate over multiple values at a time by
272 specifying a list of lexicals within parentheses:
273
274 no warnings "experimental::for_list";
275 LABEL for my (VAR, VAR) (LIST) BLOCK
276 LABEL for my (VAR, VAR) (LIST) BLOCK continue BLOCK
277 LABEL foreach my (VAR, VAR) (LIST) BLOCK
278 LABEL foreach my (VAR, VAR) (LIST) BLOCK continue BLOCK
279
280 If enabled by the experimental "try" feature, the following may also be
281 used
282
283 try BLOCK catch (VAR) BLOCK
284 try BLOCK catch (VAR) BLOCK finally BLOCK
285
286 The experimental "given" statement is not automatically enabled; see
287 "Switch Statements" below for how to do so, and the attendant caveats.
288
289 Unlike in C and Pascal, in Perl these are all defined in terms of
290 BLOCKs, not statements. This means that the curly brackets are
291 required--no dangling statements allowed. If you want to write
292 conditionals without curly brackets, there are several other ways to do
293 it. The following all do the same thing:
294
295 if (!open(FOO)) { die "Can't open $FOO: $!" }
296 die "Can't open $FOO: $!" unless open(FOO);
297 open(FOO) || die "Can't open $FOO: $!";
298 open(FOO) ? () : die "Can't open $FOO: $!";
299 # a bit exotic, that last one
300
301 The "if" statement is straightforward. Because BLOCKs are always
302 bounded by curly brackets, there is never any ambiguity about which
303 "if" an "else" goes with. If you use "unless" in place of "if", the
304 sense of the test is reversed. Like "if", "unless" can be followed by
305 "else". "unless" can even be followed by one or more "elsif"
306 statements, though you may want to think twice before using that
307 particular language construct, as everyone reading your code will have
308 to think at least twice before they can understand what's going on.
309
310 The "while" statement executes the block as long as the expression is
311 true. The "until" statement executes the block as long as the
312 expression is false. The LABEL is optional, and if present, consists
313 of an identifier followed by a colon. The LABEL identifies the loop
314 for the loop control statements "next", "last", and "redo". If the
315 LABEL is omitted, the loop control statement refers to the innermost
316 enclosing loop. This may include dynamically searching through your
317 call-stack at run time to find the LABEL. Such desperate behavior
318 triggers a warning if you use the "use warnings" pragma or the -w flag.
319
320 If the condition expression of a "while" statement is based on any of a
321 group of iterative expression types then it gets some magic treatment.
322 The affected iterative expression types are "readline", the
323 "<FILEHANDLE>" input operator, "readdir", "glob", the "<PATTERN>"
324 globbing operator, and "each". If the condition expression is one of
325 these expression types, then the value yielded by the iterative
326 operator will be implicitly assigned to $_. If the condition
327 expression is one of these expression types or an explicit assignment
328 of one of them to a scalar, then the condition actually tests for
329 definedness of the expression's value, not for its regular truth value.
330
331 If there is a "continue" BLOCK, it is always executed just before the
332 conditional is about to be evaluated again. Thus it can be used to
333 increment a loop variable, even when the loop has been continued via
334 the "next" statement.
335
336 When a block is preceded by a compilation phase keyword such as
337 "BEGIN", "END", "INIT", "CHECK", or "UNITCHECK", then the block will
338 run only during the corresponding phase of execution. See perlmod for
339 more details.
340
341 Extension modules can also hook into the Perl parser to define new
342 kinds of compound statements. These are introduced by a keyword which
343 the extension recognizes, and the syntax following the keyword is
344 defined entirely by the extension. If you are an implementor, see
345 "PL_keyword_plugin" in perlapi for the mechanism. If you are using
346 such a module, see the module's documentation for details of the syntax
347 that it defines.
348
349 Loop Control
350 The "next" command starts the next iteration of the loop:
351
352 LINE: while (<STDIN>) {
353 next LINE if /^#/; # discard comments
354 ...
355 }
356
357 The "last" command immediately exits the loop in question. The
358 "continue" block, if any, is not executed:
359
360 LINE: while (<STDIN>) {
361 last LINE if /^$/; # exit when done with header
362 ...
363 }
364
365 The "redo" command restarts the loop block without evaluating the
366 conditional again. The "continue" block, if any, is not executed.
367 This command is normally used by programs that want to lie to
368 themselves about what was just input.
369
370 For example, when processing a file like /etc/termcap. If your input
371 lines might end in backslashes to indicate continuation, you want to
372 skip ahead and get the next record.
373
374 while (<>) {
375 chomp;
376 if (s/\\$//) {
377 $_ .= <>;
378 redo unless eof();
379 }
380 # now process $_
381 }
382
383 which is Perl shorthand for the more explicitly written version:
384
385 LINE: while (defined($line = <ARGV>)) {
386 chomp($line);
387 if ($line =~ s/\\$//) {
388 $line .= <ARGV>;
389 redo LINE unless eof(); # not eof(ARGV)!
390 }
391 # now process $line
392 }
393
394 Note that if there were a "continue" block on the above code, it would
395 get executed only on lines discarded by the regex (since redo skips the
396 continue block). A continue block is often used to reset line counters
397 or "m?pat?" one-time matches:
398
399 # inspired by :1,$g/fred/s//WILMA/
400 while (<>) {
401 m?(fred)? && s//WILMA $1 WILMA/;
402 m?(barney)? && s//BETTY $1 BETTY/;
403 m?(homer)? && s//MARGE $1 MARGE/;
404 } continue {
405 print "$ARGV $.: $_";
406 close ARGV if eof; # reset $.
407 reset if eof; # reset ?pat?
408 }
409
410 If the word "while" is replaced by the word "until", the sense of the
411 test is reversed, but the conditional is still tested before the first
412 iteration.
413
414 Loop control statements don't work in an "if" or "unless", since they
415 aren't loops. You can double the braces to make them such, though.
416
417 if (/pattern/) {{
418 last if /fred/;
419 next if /barney/; # same effect as "last",
420 # but doesn't document as well
421 # do something here
422 }}
423
424 This is caused by the fact that a block by itself acts as a loop that
425 executes once, see "Basic BLOCKs".
426
427 The form "while/if BLOCK BLOCK", available in Perl 4, is no longer
428 available. Replace any occurrence of "if BLOCK" by "if (do BLOCK)".
429
430 For Loops
431 Perl's C-style "for" loop works like the corresponding "while" loop;
432 that means that this:
433
434 for ($i = 1; $i < 10; $i++) {
435 ...
436 }
437
438 is the same as this:
439
440 $i = 1;
441 while ($i < 10) {
442 ...
443 } continue {
444 $i++;
445 }
446
447 There is one minor difference: if variables are declared with "my" in
448 the initialization section of the "for", the lexical scope of those
449 variables is exactly the "for" loop (the body of the loop and the
450 control sections). To illustrate:
451
452 my $i = 'samba';
453 for (my $i = 1; $i <= 4; $i++) {
454 print "$i\n";
455 }
456 print "$i\n";
457
458 when executed, gives:
459
460 1
461 2
462 3
463 4
464 samba
465
466 As a special case, if the test in the "for" loop (or the corresponding
467 "while" loop) is empty, it is treated as true. That is, both
468
469 for (;;) {
470 ...
471 }
472
473 and
474
475 while () {
476 ...
477 }
478
479 are treated as infinite loops.
480
481 Besides the normal array index looping, "for" can lend itself to many
482 other interesting applications. Here's one that avoids the problem you
483 get into if you explicitly test for end-of-file on an interactive file
484 descriptor causing your program to appear to hang.
485
486 $on_a_tty = -t STDIN && -t STDOUT;
487 sub prompt { print "yes? " if $on_a_tty }
488 for ( prompt(); <STDIN>; prompt() ) {
489 # do something
490 }
491
492 The condition expression of a "for" loop gets the same magic treatment
493 of "readline" et al that the condition expression of a "while" loop
494 gets.
495
496 Foreach Loops
497 The "foreach" loop iterates over a normal list value and sets the
498 scalar variable VAR to be each element of the list in turn. If the
499 variable is preceded with the keyword "my", then it is lexically
500 scoped, and is therefore visible only within the loop. Otherwise, the
501 variable is implicitly local to the loop and regains its former value
502 upon exiting the loop. If the variable was previously declared with
503 "my", it uses that variable instead of the global one, but it's still
504 localized to the loop. This implicit localization occurs only for non
505 C-style loops.
506
507 The "foreach" keyword is actually a synonym for the "for" keyword, so
508 you can use either. If VAR is omitted, $_ is set to each value.
509
510 If any element of LIST is an lvalue, you can modify it by modifying VAR
511 inside the loop. Conversely, if any element of LIST is NOT an lvalue,
512 any attempt to modify that element will fail. In other words, the
513 "foreach" loop index variable is an implicit alias for each item in the
514 list that you're looping over.
515
516 If any part of LIST is an array, "foreach" will get very confused if
517 you add or remove elements within the loop body, for example with
518 "splice". So don't do that.
519
520 "foreach" probably won't do what you expect if VAR is a tied or other
521 special variable. Don't do that either.
522
523 As of Perl 5.22, there is an experimental variant of this loop that
524 accepts a variable preceded by a backslash for VAR, in which case the
525 items in the LIST must be references. The backslashed variable will
526 become an alias to each referenced item in the LIST, which must be of
527 the correct type. The variable needn't be a scalar in this case, and
528 the backslash may be followed by "my". To use this form, you must
529 enable the "refaliasing" feature via "use feature". (See feature. See
530 also "Assigning to References" in perlref.)
531
532 As of Perl 5.36, you can iterate over multiple values at a time. You
533 can only iterate with lexical scalars as the iterator variables -
534 unlike list assignment, it's not possible to use "undef" to signify a
535 value that isn't wanted. This is a limitation of the current
536 implementation, and might be changed in the future.
537
538 If the size of the LIST is not an exact multiple of the number of
539 iterator variables, then on the last iteration the "excess" iterator
540 variables are aliases to "undef", as if the LIST had ", undef" appended
541 as many times as needed for its length to become an exact multiple.
542 This happens whether LIST is a literal LIST or an array - ie arrays are
543 not extended if their size is not a multiple of the iteration size,
544 consistent with iterating an array one-at-a-time. As these padding
545 elements are not lvalues, attempting to modify them will fail,
546 consistent with the behaviour when iterating a list with literal
547 "undef"s. If this is not the behaviour you desire, then before the
548 loop starts either explicitly extend your array to be an exact
549 multiple, or explicitly throw an exception.
550
551 Examples:
552
553 for (@ary) { s/foo/bar/ }
554
555 for my $elem (@elements) {
556 $elem *= 2;
557 }
558
559 for $count (reverse(1..10), "BOOM") {
560 print $count, "\n";
561 sleep(1);
562 }
563
564 for (1..15) { print "Merry Christmas\n"; }
565
566 foreach $item (split(/:[\\\n:]*/, $ENV{TERMCAP})) {
567 print "Item: $item\n";
568 }
569
570 use feature "refaliasing";
571 no warnings "experimental::refaliasing";
572 foreach \my %hash (@array_of_hash_references) {
573 # do something with each %hash
574 }
575
576 foreach my ($foo, $bar, $baz) (@list) {
577 # do something three-at-a-time
578 }
579
580 foreach my ($key, $value) (%hash) {
581 # iterate over the hash
582 # The hash is immediately copied to a flat list before the loop
583 # starts. The list contains copies of keys but aliases of values.
584 # This is the same behaviour as for $var (%hash) {...}
585 }
586
587 Here's how a C programmer might code up a particular algorithm in Perl:
588
589 for (my $i = 0; $i < @ary1; $i++) {
590 for (my $j = 0; $j < @ary2; $j++) {
591 if ($ary1[$i] > $ary2[$j]) {
592 last; # can't go to outer :-(
593 }
594 $ary1[$i] += $ary2[$j];
595 }
596 # this is where that last takes me
597 }
598
599 Whereas here's how a Perl programmer more comfortable with the idiom
600 might do it:
601
602 OUTER: for my $wid (@ary1) {
603 INNER: for my $jet (@ary2) {
604 next OUTER if $wid > $jet;
605 $wid += $jet;
606 }
607 }
608
609 See how much easier this is? It's cleaner, safer, and faster. It's
610 cleaner because it's less noisy. It's safer because if code gets added
611 between the inner and outer loops later on, the new code won't be
612 accidentally executed. The "next" explicitly iterates the other loop
613 rather than merely terminating the inner one. And it's faster because
614 Perl executes a "foreach" statement more rapidly than it would the
615 equivalent C-style "for" loop.
616
617 Perceptive Perl hackers may have noticed that a "for" loop has a return
618 value, and that this value can be captured by wrapping the loop in a
619 "do" block. The reward for this discovery is this cautionary advice:
620 The return value of a "for" loop is unspecified and may change without
621 notice. Do not rely on it.
622
623 Try Catch Exception Handling
624 The "try"/"catch" syntax provides control flow relating to exception
625 handling. The "try" keyword introduces a block which will be executed
626 when it is encountered, and the "catch" block provides code to handle
627 any exception that may be thrown by the first.
628
629 try {
630 my $x = call_a_function();
631 $x < 100 or die "Too big";
632 send_output($x);
633 }
634 catch ($e) {
635 warn "Unable to output a value; $e";
636 }
637 print "Finished\n";
638
639 Here, the body of the "catch" block (i.e. the "warn" statement) will be
640 executed if the initial block invokes the conditional "die", or if
641 either of the functions it invokes throws an uncaught exception. The
642 "catch" block can inspect the $e lexical variable in this case to see
643 what the exception was. If no exception was thrown then the "catch"
644 block does not happen. In either case, execution will then continue
645 from the following statement - in this example the "print".
646
647 The "catch" keyword must be immediately followed by a variable
648 declaration in parentheses, which introduces a new variable visible to
649 the body of the subsequent block. Inside the block this variable will
650 contain the exception value that was thrown by the code in the "try"
651 block. It is not necessary to use the "my" keyword to declare this
652 variable; this is implied (similar as it is for subroutine signatures).
653
654 Both the "try" and the "catch" blocks are permitted to contain control-
655 flow expressions, such as "return", "goto", or "next"/"last"/"redo". In
656 all cases they behave as expected without warnings. In particular, a
657 "return" expression inside the "try" block will make its entire
658 containing function return - this is in contrast to its behaviour
659 inside an "eval" block, where it would only make that block return.
660
661 Like other control-flow syntax, "try" and "catch" will yield the last
662 evaluated value when placed as the final statement in a function or a
663 "do" block. This permits the syntax to be used to create a value. In
664 this case remember not to use the "return" expression, or that will
665 cause the containing function to return.
666
667 my $value = do {
668 try {
669 get_thing(@args);
670 }
671 catch ($e) {
672 warn "Unable to get thing - $e";
673 $DEFAULT_THING;
674 }
675 };
676
677 As with other control-flow syntax, "try" blocks are not visible to
678 caller() (just as for example, "while" or "foreach" loops are not).
679 Successive levels of the "caller" result can see subroutine calls and
680 "eval" blocks, because those affect the way that "return" would work.
681 Since "try" blocks do not intercept "return", they are not of interest
682 to "caller".
683
684 The "try" and "catch" blocks may optionally be followed by a third
685 block introduced by the "finally" keyword. This third block is executed
686 after the rest of the construct has finished.
687
688 try {
689 call_a_function();
690 }
691 catch ($e) {
692 warn "Unable to call; $e";
693 }
694 finally {
695 print "Finished\n";
696 }
697
698 The "finally" block is equivalent to using a "defer" block and will be
699 invoked in the same situations; whether the "try" block completes
700 successfully, throws an exception, or transfers control elsewhere by
701 using "return", a loop control, or "goto".
702
703 Unlike the "try" and "catch" blocks, a "finally" block is not permitted
704 to "return", "goto" or use any loop controls. The final expression
705 value is ignored, and does not affect the return value of the
706 containing function even if it is placed last in the function.
707
708 This syntax is currently experimental and must be enabled with "use
709 feature 'try'". It emits a warning in the "experimental::try" category.
710
711 Basic BLOCKs
712 A BLOCK by itself (labeled or not) is semantically equivalent to a loop
713 that executes once. Thus you can use any of the loop control
714 statements in it to leave or restart the block. (Note that this is NOT
715 true in "eval{}", "sub{}", or contrary to popular belief "do{}" blocks,
716 which do NOT count as loops.) The "continue" block is optional.
717
718 The BLOCK construct can be used to emulate case structures.
719
720 SWITCH: {
721 if (/^abc/) { $abc = 1; last SWITCH; }
722 if (/^def/) { $def = 1; last SWITCH; }
723 if (/^xyz/) { $xyz = 1; last SWITCH; }
724 $nothing = 1;
725 }
726
727 You'll also find that "foreach" loop used to create a topicalizer and a
728 switch:
729
730 SWITCH:
731 for ($var) {
732 if (/^abc/) { $abc = 1; last SWITCH; }
733 if (/^def/) { $def = 1; last SWITCH; }
734 if (/^xyz/) { $xyz = 1; last SWITCH; }
735 $nothing = 1;
736 }
737
738 Such constructs are quite frequently used, both because older versions
739 of Perl had no official "switch" statement, and also because the new
740 version described immediately below remains experimental and can
741 sometimes be confusing.
742
743 defer blocks
744 A block prefixed by the "defer" modifier provides a section of code
745 which runs at a later time during scope exit.
746
747 A "defer" block can appear at any point where a regular block or other
748 statement is permitted. If the flow of execution reaches this
749 statement, the body of the block is stored for later, but not invoked
750 immediately. When the flow of control leaves the containing block for
751 any reason, this stored block is executed on the way past. It provides
752 a means of deferring execution until a later time. This acts similarly
753 to syntax provided by some other languages, often using keywords named
754 "try / finally".
755
756 This syntax is available if enabled by the "defer" named feature, and
757 is currently experimental. If experimental warnings are enabled it will
758 emit a warning when used.
759
760 use feature 'defer';
761
762 {
763 say "This happens first";
764 defer { say "This happens last"; }
765
766 say "And this happens inbetween";
767 }
768
769 If multiple "defer" blocks are contained in a single scope, they are
770 executed in LIFO order; the last one reached is the first one executed.
771
772 The code stored by the "defer" block will be invoked when control
773 leaves its containing block due to regular fallthrough, explicit
774 "return", exceptions thrown by "die" or propagated by functions called
775 by it, "goto", or any of the loop control statements "next", "last" or
776 "redo".
777
778 If the flow of control does not reach the "defer" statement itself then
779 its body is not stored for later execution. (This is in direct contrast
780 to the code provided by an "END" phaser block, which is always enqueued
781 by the compiler, regardless of whether execution ever reached the line
782 it was given on.)
783
784 use feature 'defer';
785
786 {
787 defer { say "This will run"; }
788 return;
789 defer { say "This will not"; }
790 }
791
792 Exceptions thrown by code inside a "defer" block will propagate to the
793 caller in the same way as any other exception thrown by normal code.
794
795 If the "defer" block is being executed due to a thrown exception and
796 throws another one it is not specified what happens, beyond that the
797 caller will definitely receive an exception.
798
799 Besides throwing an exception, a "defer" block is not permitted to
800 otherwise alter the control flow of its surrounding code. In
801 particular, it may not cause its containing function to "return", nor
802 may it "goto" a label, or control a containing loop using "next",
803 "last" or "redo". These constructions are however, permitted entirely
804 within the body of the "defer".
805
806 use feature 'defer';
807
808 {
809 defer {
810 foreach ( 1 .. 5 ) {
811 last if $_ == 3; # this is permitted
812 }
813 }
814 }
815
816 {
817 foreach ( 6 .. 10 ) {
818 defer {
819 last if $_ == 8; # this is not
820 }
821 }
822 }
823
824 Switch Statements
825 Starting from Perl 5.10.1 (well, 5.10.0, but it didn't work right), you
826 can say
827
828 use feature "switch";
829
830 to enable an experimental switch feature. This is loosely based on an
831 old version of a Raku proposal, but it no longer resembles the Raku
832 construct. You also get the switch feature whenever you declare that
833 your code prefers to run under a version of Perl between 5.10 and 5.34.
834 For example:
835
836 use v5.14;
837
838 Under the "switch" feature, Perl gains the experimental keywords
839 "given", "when", "default", "continue", and "break". Starting from
840 Perl 5.16, one can prefix the switch keywords with "CORE::" to access
841 the feature without a "use feature" statement. The keywords "given"
842 and "when" are analogous to "switch" and "case" in other languages --
843 though "continue" is not -- so the code in the previous section could
844 be rewritten as
845
846 use v5.10.1;
847 for ($var) {
848 when (/^abc/) { $abc = 1 }
849 when (/^def/) { $def = 1 }
850 when (/^xyz/) { $xyz = 1 }
851 default { $nothing = 1 }
852 }
853
854 The "foreach" is the non-experimental way to set a topicalizer. If you
855 wish to use the highly experimental "given", that could be written like
856 this:
857
858 use v5.10.1;
859 given ($var) {
860 when (/^abc/) { $abc = 1 }
861 when (/^def/) { $def = 1 }
862 when (/^xyz/) { $xyz = 1 }
863 default { $nothing = 1 }
864 }
865
866 As of 5.14, that can also be written this way:
867
868 use v5.14;
869 for ($var) {
870 $abc = 1 when /^abc/;
871 $def = 1 when /^def/;
872 $xyz = 1 when /^xyz/;
873 default { $nothing = 1 }
874 }
875
876 Or if you don't care to play it safe, like this:
877
878 use v5.14;
879 given ($var) {
880 $abc = 1 when /^abc/;
881 $def = 1 when /^def/;
882 $xyz = 1 when /^xyz/;
883 default { $nothing = 1 }
884 }
885
886 The arguments to "given" and "when" are in scalar context, and "given"
887 assigns the $_ variable its topic value.
888
889 Exactly what the EXPR argument to "when" does is hard to describe
890 precisely, but in general, it tries to guess what you want done.
891 Sometimes it is interpreted as "$_ ~~ EXPR", and sometimes it is not.
892 It also behaves differently when lexically enclosed by a "given" block
893 than it does when dynamically enclosed by a "foreach" loop. The rules
894 are far too difficult to understand to be described here. See
895 "Experimental Details on given and when" later on.
896
897 Due to an unfortunate bug in how "given" was implemented between Perl
898 5.10 and 5.16, under those implementations the version of $_ governed
899 by "given" is merely a lexically scoped copy of the original, not a
900 dynamically scoped alias to the original, as it would be if it were a
901 "foreach" or under both the original and the current Raku language
902 specification. This bug was fixed in Perl 5.18 (and lexicalized $_
903 itself was removed in Perl 5.24).
904
905 If your code still needs to run on older versions, stick to "foreach"
906 for your topicalizer and you will be less unhappy.
907
908 Goto
909 Although not for the faint of heart, Perl does support a "goto"
910 statement. There are three forms: "goto"-LABEL, "goto"-EXPR, and
911 "goto"-&NAME. A loop's LABEL is not actually a valid target for a
912 "goto"; it's just the name of the loop.
913
914 The "goto"-LABEL form finds the statement labeled with LABEL and
915 resumes execution there. It may not be used to go into any construct
916 that requires initialization, such as a subroutine or a "foreach" loop.
917 It also can't be used to go into a construct that is optimized away.
918 It can be used to go almost anywhere else within the dynamic scope,
919 including out of subroutines, but it's usually better to use some other
920 construct such as "last" or "die". The author of Perl has never felt
921 the need to use this form of "goto" (in Perl, that is--C is another
922 matter).
923
924 The "goto"-EXPR form expects a label name, whose scope will be resolved
925 dynamically. This allows for computed "goto"s per FORTRAN, but isn't
926 necessarily recommended if you're optimizing for maintainability:
927
928 goto(("FOO", "BAR", "GLARCH")[$i]);
929
930 The "goto"-&NAME form is highly magical, and substitutes a call to the
931 named subroutine for the currently running subroutine. This is used by
932 AUTOLOAD() subroutines that wish to load another subroutine and then
933 pretend that the other subroutine had been called in the first place
934 (except that any modifications to @_ in the current subroutine are
935 propagated to the other subroutine.) After the "goto", not even
936 caller() will be able to tell that this routine was called first.
937
938 In almost all cases like this, it's usually a far, far better idea to
939 use the structured control flow mechanisms of "next", "last", or "redo"
940 instead of resorting to a "goto". For certain applications, the catch
941 and throw pair of "eval{}" and die() for exception processing can also
942 be a prudent approach.
943
944 The Ellipsis Statement
945 Beginning in Perl 5.12, Perl accepts an ellipsis, ""..."", as a
946 placeholder for code that you haven't implemented yet. When Perl 5.12
947 or later encounters an ellipsis statement, it parses this without
948 error, but if and when you should actually try to execute it, Perl
949 throws an exception with the text "Unimplemented":
950
951 use v5.12;
952 sub unimplemented { ... }
953 eval { unimplemented() };
954 if ($@ =~ /^Unimplemented at /) {
955 say "I found an ellipsis!";
956 }
957
958 You can only use the elliptical statement to stand in for a complete
959 statement. Syntactically, ""...;"" is a complete statement, but, as
960 with other kinds of semicolon-terminated statement, the semicolon may
961 be omitted if ""..."" appears immediately before a closing brace.
962 These examples show how the ellipsis works:
963
964 use v5.12;
965 { ... }
966 sub foo { ... }
967 ...;
968 eval { ... };
969 sub somemeth {
970 my $self = shift;
971 ...;
972 }
973 $x = do {
974 my $n;
975 ...;
976 say "Hurrah!";
977 $n;
978 };
979
980 The elliptical statement cannot stand in for an expression that is part
981 of a larger statement. These examples of attempts to use an ellipsis
982 are syntax errors:
983
984 use v5.12;
985
986 print ...;
987 open(my $fh, ">", "/dev/passwd") or ...;
988 if ($condition && ... ) { say "Howdy" };
989 ... if $a > $b;
990 say "Cromulent" if ...;
991 $flub = 5 + ...;
992
993 There are some cases where Perl can't immediately tell the difference
994 between an expression and a statement. For instance, the syntax for a
995 block and an anonymous hash reference constructor look the same unless
996 there's something in the braces to give Perl a hint. The ellipsis is a
997 syntax error if Perl doesn't guess that the "{ ... }" is a block.
998 Inside your block, you can use a ";" before the ellipsis to denote that
999 the "{ ... }" is a block and not a hash reference constructor.
1000
1001 Note: Some folks colloquially refer to this bit of punctuation as a
1002 "yada-yada" or "triple-dot", but its true name is actually an ellipsis.
1003
1004 PODs: Embedded Documentation
1005 Perl has a mechanism for intermixing documentation with source code.
1006 While it's expecting the beginning of a new statement, if the compiler
1007 encounters a line that begins with an equal sign and a word, like this
1008
1009 =head1 Here There Be Pods!
1010
1011 Then that text and all remaining text up through and including a line
1012 beginning with "=cut" will be ignored. The format of the intervening
1013 text is described in perlpod.
1014
1015 This allows you to intermix your source code and your documentation
1016 text freely, as in
1017
1018 =item snazzle($)
1019
1020 The snazzle() function will behave in the most spectacular
1021 form that you can possibly imagine, not even excepting
1022 cybernetic pyrotechnics.
1023
1024 =cut back to the compiler, nuff of this pod stuff!
1025
1026 sub snazzle($) {
1027 my $thingie = shift;
1028 .........
1029 }
1030
1031 Note that pod translators should look at only paragraphs beginning with
1032 a pod directive (it makes parsing easier), whereas the compiler
1033 actually knows to look for pod escapes even in the middle of a
1034 paragraph. This means that the following secret stuff will be ignored
1035 by both the compiler and the translators.
1036
1037 $a=3;
1038 =secret stuff
1039 warn "Neither POD nor CODE!?"
1040 =cut back
1041 print "got $a\n";
1042
1043 You probably shouldn't rely upon the warn() being podded out forever.
1044 Not all pod translators are well-behaved in this regard, and perhaps
1045 the compiler will become pickier.
1046
1047 One may also use pod directives to quickly comment out a section of
1048 code.
1049
1050 Plain Old Comments (Not!)
1051 Perl can process line directives, much like the C preprocessor. Using
1052 this, one can control Perl's idea of filenames and line numbers in
1053 error or warning messages (especially for strings that are processed
1054 with eval()). The syntax for this mechanism is almost the same as for
1055 most C preprocessors: it matches the regular expression
1056
1057 # example: '# line 42 "new_filename.plx"'
1058 /^\# \s*
1059 line \s+ (\d+) \s*
1060 (?:\s("?)([^"]+)\g2)? \s*
1061 $/x
1062
1063 with $1 being the line number for the next line, and $3 being the
1064 optional filename (specified with or without quotes). Note that no
1065 whitespace may precede the "#", unlike modern C preprocessors.
1066
1067 There is a fairly obvious gotcha included with the line directive:
1068 Debuggers and profilers will only show the last source line to appear
1069 at a particular line number in a given file. Care should be taken not
1070 to cause line number collisions in code you'd like to debug later.
1071
1072 Here are some examples that you should be able to type into your
1073 command shell:
1074
1075 % perl
1076 # line 200 "bzzzt"
1077 # the '#' on the previous line must be the first char on line
1078 die 'foo';
1079 __END__
1080 foo at bzzzt line 201.
1081
1082 % perl
1083 # line 200 "bzzzt"
1084 eval qq[\n#line 2001 ""\ndie 'foo']; print $@;
1085 __END__
1086 foo at - line 2001.
1087
1088 % perl
1089 eval qq[\n#line 200 "foo bar"\ndie 'foo']; print $@;
1090 __END__
1091 foo at foo bar line 200.
1092
1093 % perl
1094 # line 345 "goop"
1095 eval "\n#line " . __LINE__ . ' "' . __FILE__ ."\"\ndie 'foo'";
1096 print $@;
1097 __END__
1098 foo at goop line 345.
1099
1100 Experimental Details on given and when
1101 As previously mentioned, the "switch" feature is considered highly
1102 experimental (it is also scheduled to be removed in perl 5.42.0); it is
1103 subject to change with little notice. In particular, "when" has tricky
1104 behaviours that are expected to change to become less tricky in the
1105 future. Do not rely upon its current (mis)implementation. Before Perl
1106 5.18, "given" also had tricky behaviours that you should still beware
1107 of if your code must run on older versions of Perl.
1108
1109 Here is a longer example of "given":
1110
1111 use feature ":5.10";
1112 given ($foo) {
1113 when (undef) {
1114 say '$foo is undefined';
1115 }
1116 when ("foo") {
1117 say '$foo is the string "foo"';
1118 }
1119 when ([1,3,5,7,9]) {
1120 say '$foo is an odd digit';
1121 continue; # Fall through
1122 }
1123 when ($_ < 100) {
1124 say '$foo is numerically less than 100';
1125 }
1126 when (\&complicated_check) {
1127 say 'a complicated check for $foo is true';
1128 }
1129 default {
1130 die q(I don't know what to do with $foo);
1131 }
1132 }
1133
1134 Before Perl 5.18, given(EXPR) assigned the value of EXPR to merely a
1135 lexically scoped copy (!) of $_, not a dynamically scoped alias the way
1136 "foreach" does. That made it similar to
1137
1138 do { my $_ = EXPR; ... }
1139
1140 except that the block was automatically broken out of by a successful
1141 "when" or an explicit "break". Because it was only a copy, and because
1142 it was only lexically scoped, not dynamically scoped, you could not do
1143 the things with it that you are used to in a "foreach" loop. In
1144 particular, it did not work for arbitrary function calls if those
1145 functions might try to access $_. Best stick to "foreach" for that.
1146
1147 Most of the power comes from the implicit smartmatching that can
1148 sometimes apply. Most of the time, when(EXPR) is treated as an
1149 implicit smartmatch of $_, that is, "$_ ~~ EXPR". (See "Smartmatch
1150 Operator" in perlop for more information on smartmatching.) But when
1151 EXPR is one of the 10 exceptional cases (or things like them) listed
1152 below, it is used directly as a boolean.
1153
1154 1. A user-defined subroutine call or a method invocation.
1155
1156 2. A regular expression match in the form of "/REGEX/", "$foo =~
1157 /REGEX/", or "$foo =~ EXPR". Also, a negated regular expression
1158 match in the form "!/REGEX/", "$foo !~ /REGEX/", or "$foo !~ EXPR".
1159
1160 3. A smart match that uses an explicit "~~" operator, such as "EXPR ~~
1161 EXPR".
1162
1163 NOTE: You will often have to use "$c ~~ $_" because the default
1164 case uses "$_ ~~ $c" , which is frequently the opposite of what you
1165 want.
1166
1167 4. A boolean comparison operator such as "$_ < 10" or "$x eq "abc"".
1168 The relational operators that this applies to are the six numeric
1169 comparisons ("<", ">", "<=", ">=", "==", and "!="), and the six
1170 string comparisons ("lt", "gt", "le", "ge", "eq", and "ne").
1171
1172 5. At least the three builtin functions defined(...), exists(...), and
1173 eof(...). We might someday add more of these later if we think of
1174 them.
1175
1176 6. A negated expression, whether "!(EXPR)" or not(EXPR), or a logical
1177 exclusive-or, "(EXPR1) xor (EXPR2)". The bitwise versions ("~" and
1178 "^") are not included.
1179
1180 7. A filetest operator, with exactly 4 exceptions: "-s", "-M", "-A",
1181 and "-C", as these return numerical values, not boolean ones. The
1182 "-z" filetest operator is not included in the exception list.
1183
1184 8. The ".." and "..." flip-flop operators. Note that the "..." flip-
1185 flop operator is completely different from the "..." elliptical
1186 statement just described.
1187
1188 In those 8 cases above, the value of EXPR is used directly as a
1189 boolean, so no smartmatching is done. You may think of "when" as a
1190 smartsmartmatch.
1191
1192 Furthermore, Perl inspects the operands of logical operators to decide
1193 whether to use smartmatching for each one by applying the above test to
1194 the operands:
1195
1196 9. If EXPR is "EXPR1 && EXPR2" or "EXPR1 and EXPR2", the test is
1197 applied recursively to both EXPR1 and EXPR2. Only if both operands
1198 also pass the test, recursively, will the expression be treated as
1199 boolean. Otherwise, smartmatching is used.
1200
1201 10. If EXPR is "EXPR1 || EXPR2", "EXPR1 // EXPR2", or "EXPR1 or EXPR2",
1202 the test is applied recursively to EXPR1 only (which might itself
1203 be a higher-precedence AND operator, for example, and thus subject
1204 to the previous rule), not to EXPR2. If EXPR1 is to use
1205 smartmatching, then EXPR2 also does so, no matter what EXPR2
1206 contains. But if EXPR2 does not get to use smartmatching, then the
1207 second argument will not be either. This is quite different from
1208 the "&&" case just described, so be careful.
1209
1210 These rules are complicated, but the goal is for them to do what you
1211 want (even if you don't quite understand why they are doing it). For
1212 example:
1213
1214 when (/^\d+$/ && $_ < 75) { ... }
1215
1216 will be treated as a boolean match because the rules say both a regex
1217 match and an explicit test on $_ will be treated as boolean.
1218
1219 Also:
1220
1221 when ([qw(foo bar)] && /baz/) { ... }
1222
1223 will use smartmatching because only one of the operands is a boolean:
1224 the other uses smartmatching, and that wins.
1225
1226 Further:
1227
1228 when ([qw(foo bar)] || /^baz/) { ... }
1229
1230 will use smart matching (only the first operand is considered), whereas
1231
1232 when (/^baz/ || [qw(foo bar)]) { ... }
1233
1234 will test only the regex, which causes both operands to be treated as
1235 boolean. Watch out for this one, then, because an arrayref is always a
1236 true value, which makes it effectively redundant. Not a good idea.
1237
1238 Tautologous boolean operators are still going to be optimized away.
1239 Don't be tempted to write
1240
1241 when ("foo" or "bar") { ... }
1242
1243 This will optimize down to "foo", so "bar" will never be considered
1244 (even though the rules say to use a smartmatch on "foo"). For an
1245 alternation like this, an array ref will work, because this will
1246 instigate smartmatching:
1247
1248 when ([qw(foo bar)] { ... }
1249
1250 This is somewhat equivalent to the C-style switch statement's
1251 fallthrough functionality (not to be confused with Perl's fallthrough
1252 functionality--see below), wherein the same block is used for several
1253 "case" statements.
1254
1255 Another useful shortcut is that, if you use a literal array or hash as
1256 the argument to "given", it is turned into a reference. So given(@foo)
1257 is the same as given(\@foo), for example.
1258
1259 "default" behaves exactly like "when(1 == 1)", which is to say that it
1260 always matches.
1261
1262 Breaking out
1263
1264 You can use the "break" keyword to break out of the enclosing "given"
1265 block. Every "when" block is implicitly ended with a "break".
1266
1267 Fall-through
1268
1269 You can use the "continue" keyword to fall through from one case to the
1270 next immediate "when" or "default":
1271
1272 given($foo) {
1273 when (/x/) { say '$foo contains an x'; continue }
1274 when (/y/) { say '$foo contains a y' }
1275 default { say '$foo does not contain a y' }
1276 }
1277
1278 Return value
1279
1280 When a "given" statement is also a valid expression (for example, when
1281 it's the last statement of a block), it evaluates to:
1282
1283 • An empty list as soon as an explicit "break" is encountered.
1284
1285 • The value of the last evaluated expression of the successful
1286 "when"/"default" clause, if there happens to be one.
1287
1288 • The value of the last evaluated expression of the "given" block if
1289 no condition is true.
1290
1291 In both last cases, the last expression is evaluated in the context
1292 that was applied to the "given" block.
1293
1294 Note that, unlike "if" and "unless", failed "when" statements always
1295 evaluate to an empty list.
1296
1297 my $price = do {
1298 given ($item) {
1299 when (["pear", "apple"]) { 1 }
1300 break when "vote"; # My vote cannot be bought
1301 1e10 when /Mona Lisa/;
1302 "unknown";
1303 }
1304 };
1305
1306 Currently, "given" blocks can't always be used as proper expressions.
1307 This may be addressed in a future version of Perl.
1308
1309 Switching in a loop
1310
1311 Instead of using given(), you can use a foreach() loop. For example,
1312 here's one way to count how many times a particular string occurs in an
1313 array:
1314
1315 use v5.10.1;
1316 my $count = 0;
1317 for (@array) {
1318 when ("foo") { ++$count }
1319 }
1320 print "\@array contains $count copies of 'foo'\n";
1321
1322 Or in a more recent version:
1323
1324 use v5.14;
1325 my $count = 0;
1326 for (@array) {
1327 ++$count when "foo";
1328 }
1329 print "\@array contains $count copies of 'foo'\n";
1330
1331 At the end of all "when" blocks, there is an implicit "next". You can
1332 override that with an explicit "last" if you're interested in only the
1333 first match alone.
1334
1335 This doesn't work if you explicitly specify a loop variable, as in "for
1336 $item (@array)". You have to use the default variable $_.
1337
1338 Differences from Raku
1339
1340 The Perl 5 smartmatch and "given"/"when" constructs are not compatible
1341 with their Raku analogues. The most visible difference and least
1342 important difference is that, in Perl 5, parentheses are required
1343 around the argument to given() and when() (except when this last one is
1344 used as a statement modifier). Parentheses in Raku are always optional
1345 in a control construct such as if(), while(), or when(); they can't be
1346 made optional in Perl 5 without a great deal of potential confusion,
1347 because Perl 5 would parse the expression
1348
1349 given $foo {
1350 ...
1351 }
1352
1353 as though the argument to "given" were an element of the hash %foo,
1354 interpreting the braces as hash-element syntax.
1355
1356 However, their are many, many other differences. For example, this
1357 works in Perl 5:
1358
1359 use v5.12;
1360 my @primary = ("red", "blue", "green");
1361
1362 if (@primary ~~ "red") {
1363 say "primary smartmatches red";
1364 }
1365
1366 if ("red" ~~ @primary) {
1367 say "red smartmatches primary";
1368 }
1369
1370 say "that's all, folks!";
1371
1372 But it doesn't work at all in Raku. Instead, you should use the
1373 (parallelizable) "any" operator:
1374
1375 if any(@primary) eq "red" {
1376 say "primary smartmatches red";
1377 }
1378
1379 if "red" eq any(@primary) {
1380 say "red smartmatches primary";
1381 }
1382
1383 The table of smartmatches in "Smartmatch Operator" in perlop is not
1384 identical to that proposed by the Raku specification, mainly due to
1385 differences between Raku's and Perl 5's data models, but also because
1386 the Raku spec has changed since Perl 5 rushed into early adoption.
1387
1388 In Raku, when() will always do an implicit smartmatch with its
1389 argument, while in Perl 5 it is convenient (albeit potentially
1390 confusing) to suppress this implicit smartmatch in various rather
1391 loosely-defined situations, as roughly outlined above. (The difference
1392 is largely because Perl 5 does not have, even internally, a boolean
1393 type.)
1394
1395
1396
1397perl v5.38.2 2023-11-30 PERLSYN(1)