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