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