.\" -*- mode: troff; coding: utf-8 -*- .\" Automatically generated by Pod::Man 5.01 (Pod::Simple 3.43) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>. .ie n \{\ . ds C` "" . ds C' "" 'br\} .el\{\ . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "PERLSYN 1perl" .TH PERLSYN 1perl 2024-02-11 "perl v5.38.2" "Perl Programmers Reference Guide" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH NAME perlsyn \- Perl syntax .IX Xref "syntax" .SH DESCRIPTION .IX Header "DESCRIPTION" A Perl program consists of a sequence of declarations and statements which run from the top to the bottom. Loops, subroutines, and other control structures allow you to jump around within the code. .PP Perl is a \fBfree-form\fR language: you can format and indent it however you like. Whitespace serves mostly to separate tokens, unlike languages like Python where it is an important part of the syntax, or Fortran where it is immaterial. .PP Many of Perl's syntactic elements are \fBoptional\fR. Rather than requiring you to put parentheses around every function call and declare every variable, you can often leave such explicit elements off and Perl will figure out what you meant. This is known as \fBDo What I Mean\fR, abbreviated \fBDWIM\fR. It allows programmers to be \fBlazy\fR and to code in a style with which they are comfortable. .PP Perl \fBborrows syntax\fR and concepts from many languages: awk, sed, C, Bourne Shell, Smalltalk, Lisp and even English. Other languages have borrowed syntax from Perl, particularly its regular expression extensions. So if you have programmed in another language you will see familiar pieces in Perl. They often work the same, but see perltrap for information about how they differ. .SS Declarations .IX Xref "declaration undef undefined uninitialized" .IX Subsection "Declarations" The only things you need to declare in Perl are report formats and subroutines (and sometimes not even subroutines). A scalar variable holds the undefined value (\f(CW\*(C`undef\*(C'\fR) until it has been assigned a defined value, which is anything other than \f(CW\*(C`undef\*(C'\fR. When used as a number, \&\f(CW\*(C`undef\*(C'\fR is treated as \f(CW0\fR; when used as a string, it is treated as the empty string, \f(CW""\fR; and when used as a reference that isn't being assigned to, it is treated as an error. If you enable warnings, you'll be notified of an uninitialized value whenever you treat \&\f(CW\*(C`undef\*(C'\fR as a string or a number. Well, usually. Boolean contexts, such as: .PP .Vb 1 \& if ($a) {} .Ve .PP are exempt from warnings (because they care about truth rather than definedness). Operators such as \f(CW\*(C`++\*(C'\fR, \f(CW\*(C`\-\-\*(C'\fR, \f(CW\*(C`+=\*(C'\fR, \&\f(CW\*(C`\-=\*(C'\fR, and \f(CW\*(C`.=\*(C'\fR, that operate on undefined variables such as: .PP .Vb 2 \& undef $a; \& $a++; .Ve .PP are also always exempt from such warnings. .PP A declaration can be put anywhere a statement can, but has no effect on the execution of the primary sequence of statements: declarations all take effect at compile time. All declarations are typically put at the beginning or the end of the script. However, if you're using lexically-scoped private variables created with \f(CWmy()\fR, \&\f(CWstate()\fR, or \f(CWour()\fR, you'll have to make sure your format or subroutine definition is within the same block scope as the my if you expect to be able to access those private variables. .PP Declaring a subroutine allows a subroutine name to be used as if it were a list operator from that point forward in the program. You can declare a subroutine without defining it by saying \f(CW\*(C`sub name\*(C'\fR, thus: .IX Xref "subroutine, declaration" .PP .Vb 2 \& sub myname; \& $me = myname $0 or die "can\*(Aqt get myname"; .Ve .PP A bare declaration like that declares the function to be a list operator, not a unary operator, so you have to be careful to use parentheses (or \&\f(CW\*(C`or\*(C'\fR instead of \f(CW\*(C`||\*(C'\fR.) The \f(CW\*(C`||\*(C'\fR operator binds too tightly to use after list operators; it becomes part of the last element. You can always use parentheses around the list operators arguments to turn the list operator back into something that behaves more like a function call. Alternatively, you can use the prototype \f(CW\*(C`($)\*(C'\fR to turn the subroutine into a unary operator: .PP .Vb 2 \& sub myname ($); \& $me = myname $0 || die "can\*(Aqt get myname"; .Ve .PP That now parses as you'd expect, but you still ought to get in the habit of using parentheses in that situation. For more on prototypes, see perlsub. .PP Subroutines declarations can also be loaded up with the \f(CW\*(C`require\*(C'\fR statement or both loaded and imported into your namespace with a \f(CW\*(C`use\*(C'\fR statement. See perlmod for details on this. .PP A statement sequence may contain declarations of lexically-scoped variables, but apart from declaring a variable name, the declaration acts like an ordinary statement, and is elaborated within the sequence of statements as if it were an ordinary statement. That means it actually has both compile-time and run-time effects. .SS Comments .IX Xref "comment #" .IX Subsection "Comments" Text from a \f(CW"#"\fR character until the end of the line is a comment, and is ignored. Exceptions include \f(CW"#"\fR inside a string or regular expression. .SS "Simple Statements" .IX Xref "statement semicolon expression ;" .IX Subsection "Simple Statements" The only kind of simple statement is an expression evaluated for its side-effects. Every simple statement must be terminated with a semicolon, unless it is the final statement in a block, in which case the semicolon is optional. But put the semicolon in anyway if the block takes up more than one line, because you may eventually add another line. Note that there are operators like \f(CW\*(C`eval {}\*(C'\fR, \f(CW\*(C`sub {}\*(C'\fR, and \&\f(CW\*(C`do {}\*(C'\fR that \fIlook\fR like compound statements, but aren't\-\-they're just TERMs in an expression\-\-and thus need an explicit termination when used as the last item in a statement. .SS "Statement Modifiers" .IX Xref "statement modifier modifier if unless while until when foreach for" .IX Subsection "Statement Modifiers" Any simple statement may optionally be followed by a \fISINGLE\fR modifier, just before the terminating semicolon (or block ending). The possible modifiers are: .PP .Vb 7 \& if EXPR \& unless EXPR \& while EXPR \& until EXPR \& for LIST \& foreach LIST \& when EXPR .Ve .PP The \f(CW\*(C`EXPR\*(C'\fR following the modifier is referred to as the "condition". Its truth or falsehood determines how the modifier will behave. .PP \&\f(CW\*(C`if\*(C'\fR executes the statement once \fIif\fR and only if the condition is true. \f(CW\*(C`unless\*(C'\fR is the opposite, it executes the statement \fIunless\fR the condition is true (that is, if the condition is false). See "Scalar values" in perldata for definitions of true and false. .PP .Vb 2 \& print "Basset hounds got long ears" if length $ear >= 10; \& go_outside() and play() unless $is_raining; .Ve .PP The \f(CWfor(each)\fR modifier is an iterator: it executes the statement once for each item in the LIST (with \f(CW$_\fR aliased to each item in turn). There is no syntax to specify a C\-style for loop or a lexically scoped iteration variable in this form. .PP .Vb 1 \& print "Hello $_!\en" for qw(world Dolly nurse); .Ve .PP \&\f(CW\*(C`while\*(C'\fR repeats the statement \fIwhile\fR the condition is true. Postfix \f(CW\*(C`while\*(C'\fR has the same magic treatment of some kinds of condition that prefix \f(CW\*(C`while\*(C'\fR has. \&\f(CW\*(C`until\*(C'\fR does the opposite, it repeats the statement \fIuntil\fR the condition is true (or while the condition is false): .PP .Vb 3 \& # Both of these count from 0 to 10. \& print $i++ while $i <= 10; \& print $j++ until $j > 10; .Ve .PP The \f(CW\*(C`while\*(C'\fR and \f(CW\*(C`until\*(C'\fR modifiers have the usual "\f(CW\*(C`while\*(C'\fR loop" semantics (conditional evaluated first), except when applied to a \&\f(CW\*(C`do\*(C'\fR\-BLOCK (or to the Perl4 \f(CW\*(C`do\*(C'\fR\-SUBROUTINE statement), in which case the block executes once before the conditional is evaluated. .PP This is so that you can write loops like: .PP .Vb 4 \& do { \& $line = ; \& ... \& } until !defined($line) || $line eq ".\en" .Ve .PP See "do" in perlfunc. Note also that the loop control statements described later will \fINOT\fR work in this construct, because modifiers don't take loop labels. Sorry. You can always put another block inside of it (for \f(CW\*(C`next\*(C'\fR/\f(CW\*(C`redo\*(C'\fR) or around it (for \f(CW\*(C`last\*(C'\fR) to do that sort of thing. .IX Xref "next last redo" .PP For \f(CW\*(C`next\*(C'\fR or \f(CW\*(C`redo\*(C'\fR, just double the braces: .PP .Vb 4 \& do {{ \& next if $x == $y; \& # do something here \& }} until $x++ > $z; .Ve .PP For \f(CW\*(C`last\*(C'\fR, you have to be more elaborate and put braces around it: .IX Xref "last" .PP .Vb 6 \& { \& do { \& last if $x == $y**2; \& # do something here \& } while $x++ <= $z; \& } .Ve .PP If you need both \f(CW\*(C`next\*(C'\fR and \f(CW\*(C`last\*(C'\fR, you have to do both and also use a loop label: .PP .Vb 7 \& LOOP: { \& do {{ \& next if $x == $y; \& last LOOP if $x == $y**2; \& # do something here \& }} until $x++ > $z; \& } .Ve .PP \&\fBNOTE:\fR The behaviour of a \f(CW\*(C`my\*(C'\fR, \f(CW\*(C`state\*(C'\fR, or \&\f(CW\*(C`our\*(C'\fR modified with a statement modifier conditional or loop construct (for example, \f(CW\*(C`my $x if ...\*(C'\fR) is \&\fBundefined\fR. The value of the \f(CW\*(C`my\*(C'\fR variable may be \f(CW\*(C`undef\*(C'\fR, any previously assigned value, or possibly anything else. Don't rely on it. Future versions of perl might do something different from the version of perl you try it out on. Here be dragons. .IX Xref "my" .PP The \f(CW\*(C`when\*(C'\fR modifier is an experimental feature that first appeared in Perl 5.14. To use it, you should include a \f(CW\*(C`use v5.14\*(C'\fR declaration. (Technically, it requires only the \f(CW\*(C`switch\*(C'\fR feature, but that aspect of it was not available before 5.14.) Operative only from within a \f(CW\*(C`foreach\*(C'\fR loop or a \f(CW\*(C`given\*(C'\fR block, it executes the statement only if the smartmatch \&\f(CW\*(C`$_ ~~ \fR\f(CIEXPR\fR\f(CW\*(C'\fR is true. If the statement executes, it is followed by a \f(CW\*(C`next\*(C'\fR from inside a \f(CW\*(C`foreach\*(C'\fR and \f(CW\*(C`break\*(C'\fR from inside a \f(CW\*(C`given\*(C'\fR. .PP Under the current implementation, the \f(CW\*(C`foreach\*(C'\fR loop can be anywhere within the \f(CW\*(C`when\*(C'\fR modifier's dynamic scope, but must be within the \f(CW\*(C`given\*(C'\fR block's lexical scope. This restriction may be relaxed in a future release. See "Switch Statements" below. .SS "Compound Statements" .IX Xref "statement, compound block bracket, curly curly bracket brace { } if unless given while until foreach for continue" .IX Subsection "Compound Statements" In Perl, a sequence of statements that defines a scope is called a block. Sometimes a block is delimited by the file containing it (in the case of a required file, or the program as a whole), and sometimes a block is delimited by the extent of a string (in the case of an eval). .PP But generally, a block is delimited by curly brackets, also known as braces. We will call this syntactic construct a BLOCK. Because enclosing braces are also the syntax for hash reference constructor expressions (see perlref), you may occasionally need to disambiguate by placing a \&\f(CW\*(C`;\*(C'\fR immediately after an opening brace so that Perl realises the brace is the start of a block. You will more frequently need to disambiguate the other way, by placing a \f(CW\*(C`+\*(C'\fR immediately before an opening brace to force it to be interpreted as a hash reference constructor expression. It is considered good style to use these disambiguating mechanisms liberally, not only when Perl would otherwise guess incorrectly. .PP The following compound statements may be used to control flow: .PP .Vb 4 \& if (EXPR) BLOCK \& if (EXPR) BLOCK else BLOCK \& if (EXPR) BLOCK elsif (EXPR) BLOCK ... \& if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK \& \& unless (EXPR) BLOCK \& unless (EXPR) BLOCK else BLOCK \& unless (EXPR) BLOCK elsif (EXPR) BLOCK ... \& unless (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK \& \& given (EXPR) BLOCK \& \& LABEL while (EXPR) BLOCK \& LABEL while (EXPR) BLOCK continue BLOCK \& \& LABEL until (EXPR) BLOCK \& LABEL until (EXPR) BLOCK continue BLOCK \& \& LABEL for (EXPR; EXPR; EXPR) BLOCK \& LABEL for VAR (LIST) BLOCK \& LABEL for VAR (LIST) BLOCK continue BLOCK \& \& LABEL foreach (EXPR; EXPR; EXPR) BLOCK \& LABEL foreach VAR (LIST) BLOCK \& LABEL foreach VAR (LIST) BLOCK continue BLOCK \& \& LABEL BLOCK \& LABEL BLOCK continue BLOCK \& \& PHASE BLOCK .Ve .PP As of Perl 5.36, you can iterate over multiple values at a time by specifying a list of lexicals within parentheses: .PP .Vb 5 \& no warnings "experimental::for_list"; \& LABEL for my (VAR, VAR) (LIST) BLOCK \& LABEL for my (VAR, VAR) (LIST) BLOCK continue BLOCK \& LABEL foreach my (VAR, VAR) (LIST) BLOCK \& LABEL foreach my (VAR, VAR) (LIST) BLOCK continue BLOCK .Ve .PP If enabled by the experimental \f(CW\*(C`try\*(C'\fR feature, the following may also be used .PP .Vb 2 \& try BLOCK catch (VAR) BLOCK \& try BLOCK catch (VAR) BLOCK finally BLOCK .Ve .PP The experimental \f(CW\*(C`given\*(C'\fR statement is \fInot automatically enabled\fR; see "Switch Statements" below for how to do so, and the attendant caveats. .PP Unlike in C and Pascal, in Perl these are all defined in terms of BLOCKs, not statements. This means that the curly brackets are \fIrequired\fR\-\-no dangling statements allowed. If you want to write conditionals without curly brackets, there are several other ways to do it. The following all do the same thing: .PP .Vb 5 \& if (!open(FOO)) { die "Can\*(Aqt open $FOO: $!" } \& die "Can\*(Aqt open $FOO: $!" unless open(FOO); \& open(FOO) || die "Can\*(Aqt open $FOO: $!"; \& open(FOO) ? () : die "Can\*(Aqt open $FOO: $!"; \& # a bit exotic, that last one .Ve .PP The \f(CW\*(C`if\*(C'\fR statement is straightforward. Because BLOCKs are always bounded by curly brackets, there is never any ambiguity about which \&\f(CW\*(C`if\*(C'\fR an \f(CW\*(C`else\*(C'\fR goes with. If you use \f(CW\*(C`unless\*(C'\fR in place of \f(CW\*(C`if\*(C'\fR, the sense of the test is reversed. Like \f(CW\*(C`if\*(C'\fR, \f(CW\*(C`unless\*(C'\fR can be followed by \f(CW\*(C`else\*(C'\fR. \f(CW\*(C`unless\*(C'\fR can even be followed by one or more \f(CW\*(C`elsif\*(C'\fR statements, though you may want to think twice before using that particular language construct, as everyone reading your code will have to think at least twice before they can understand what's going on. .PP The \f(CW\*(C`while\*(C'\fR statement executes the block as long as the expression is true. The \f(CW\*(C`until\*(C'\fR statement executes the block as long as the expression is false. The LABEL is optional, and if present, consists of an identifier followed by a colon. The LABEL identifies the loop for the loop control statements \f(CW\*(C`next\*(C'\fR, \f(CW\*(C`last\*(C'\fR, and \f(CW\*(C`redo\*(C'\fR. If the LABEL is omitted, the loop control statement refers to the innermost enclosing loop. This may include dynamically searching through your call-stack at run time to find the LABEL. Such desperate behavior triggers a warning if you use the \f(CW\*(C`use warnings\*(C'\fR pragma or the \fB\-w\fR flag. .PP If the condition expression of a \f(CW\*(C`while\*(C'\fR statement is based on any of a group of iterative expression types then it gets some magic treatment. The affected iterative expression types are \f(CW\*(C`readline\*(C'\fR, the \f(CW\*(C`\*(C'\fR input operator, \f(CW\*(C`readdir\*(C'\fR, \f(CW\*(C`glob\*(C'\fR, the \f(CW\*(C`\*(C'\fR globbing operator, and \f(CW\*(C`each\*(C'\fR. If the condition expression is one of these expression types, then the value yielded by the iterative operator will be implicitly assigned to \f(CW$_\fR. If the condition expression is one of these expression types or an explicit assignment of one of them to a scalar, then the condition actually tests for definedness of the expression's value, not for its regular truth value. .PP If there is a \f(CW\*(C`continue\*(C'\fR BLOCK, it is always executed just before the conditional is about to be evaluated again. Thus it can be used to increment a loop variable, even when the loop has been continued via the \f(CW\*(C`next\*(C'\fR statement. .PP When a block is preceded by a compilation phase keyword such as \f(CW\*(C`BEGIN\*(C'\fR, \&\f(CW\*(C`END\*(C'\fR, \f(CW\*(C`INIT\*(C'\fR, \f(CW\*(C`CHECK\*(C'\fR, or \f(CW\*(C`UNITCHECK\*(C'\fR, then the block will run only during the corresponding phase of execution. See perlmod for more details. .PP Extension modules can also hook into the Perl parser to define new kinds of compound statements. These are introduced by a keyword which the extension recognizes, and the syntax following the keyword is defined entirely by the extension. If you are an implementor, see "PL_keyword_plugin" in perlapi for the mechanism. If you are using such a module, see the module's documentation for details of the syntax that it defines. .SS "Loop Control" .IX Xref "loop control loop, control next last redo continue" .IX Subsection "Loop Control" The \f(CW\*(C`next\*(C'\fR command starts the next iteration of the loop: .PP .Vb 4 \& LINE: while () { \& next LINE if /^#/; # discard comments \& ... \& } .Ve .PP The \f(CW\*(C`last\*(C'\fR command immediately exits the loop in question. The \&\f(CW\*(C`continue\*(C'\fR block, if any, is not executed: .PP .Vb 4 \& LINE: while () { \& last LINE if /^$/; # exit when done with header \& ... \& } .Ve .PP The \f(CW\*(C`redo\*(C'\fR command restarts the loop block without evaluating the conditional again. The \f(CW\*(C`continue\*(C'\fR block, if any, is \fInot\fR executed. This command is normally used by programs that want to lie to themselves about what was just input. .PP For example, when processing a file like \fI/etc/termcap\fR. If your input lines might end in backslashes to indicate continuation, you want to skip ahead and get the next record. .PP .Vb 8 \& while (<>) { \& chomp; \& if (s/\e\e$//) { \& $_ .= <>; \& redo unless eof(); \& } \& # now process $_ \& } .Ve .PP which is Perl shorthand for the more explicitly written version: .PP .Vb 8 \& LINE: while (defined($line = )) { \& chomp($line); \& if ($line =~ s/\e\e$//) { \& $line .= ; \& redo LINE unless eof(); # not eof(ARGV)! \& } \& # now process $line \& } .Ve .PP Note that if there were a \f(CW\*(C`continue\*(C'\fR block on the above code, it would get executed only on lines discarded by the regex (since redo skips the continue block). A continue block is often used to reset line counters or \f(CW\*(C`m?pat?\*(C'\fR one-time matches: .PP .Vb 10 \& # inspired by :1,$g/fred/s//WILMA/ \& while (<>) { \& m?(fred)? && s//WILMA $1 WILMA/; \& m?(barney)? && s//BETTY $1 BETTY/; \& m?(homer)? && s//MARGE $1 MARGE/; \& } continue { \& print "$ARGV $.: $_"; \& close ARGV if eof; # reset $. \& reset if eof; # reset ?pat? \& } .Ve .PP If the word \f(CW\*(C`while\*(C'\fR is replaced by the word \f(CW\*(C`until\*(C'\fR, the sense of the test is reversed, but the conditional is still tested before the first iteration. .PP Loop control statements don't work in an \f(CW\*(C`if\*(C'\fR or \f(CW\*(C`unless\*(C'\fR, since they aren't loops. You can double the braces to make them such, though. .PP .Vb 6 \& if (/pattern/) {{ \& last if /fred/; \& next if /barney/; # same effect as "last", \& # but doesn\*(Aqt document as well \& # do something here \& }} .Ve .PP This is caused by the fact that a block by itself acts as a loop that executes once, see "Basic BLOCKs". .PP The form \f(CW\*(C`while/if BLOCK BLOCK\*(C'\fR, available in Perl 4, is no longer available. Replace any occurrence of \f(CW\*(C`if BLOCK\*(C'\fR by \f(CW\*(C`if (do BLOCK)\*(C'\fR. .SS "For Loops" .IX Xref "for foreach" .IX Subsection "For Loops" Perl's C\-style \f(CW\*(C`for\*(C'\fR loop works like the corresponding \f(CW\*(C`while\*(C'\fR loop; that means that this: .PP .Vb 3 \& for ($i = 1; $i < 10; $i++) { \& ... \& } .Ve .PP is the same as this: .PP .Vb 6 \& $i = 1; \& while ($i < 10) { \& ... \& } continue { \& $i++; \& } .Ve .PP There is one minor difference: if variables are declared with \f(CW\*(C`my\*(C'\fR in the initialization section of the \f(CW\*(C`for\*(C'\fR, the lexical scope of those variables is exactly the \f(CW\*(C`for\*(C'\fR loop (the body of the loop and the control sections). To illustrate: .IX Xref "my" .PP .Vb 5 \& my $i = \*(Aqsamba\*(Aq; \& for (my $i = 1; $i <= 4; $i++) { \& print "$i\en"; \& } \& print "$i\en"; .Ve .PP when executed, gives: .PP .Vb 5 \& 1 \& 2 \& 3 \& 4 \& samba .Ve .PP As a special case, if the test in the \f(CW\*(C`for\*(C'\fR loop (or the corresponding \&\f(CW\*(C`while\*(C'\fR loop) is empty, it is treated as true. That is, both .PP .Vb 3 \& for (;;) { \& ... \& } .Ve .PP and .PP .Vb 3 \& while () { \& ... \& } .Ve .PP are treated as infinite loops. .PP Besides the normal array index looping, \f(CW\*(C`for\*(C'\fR can lend itself to many other interesting applications. Here's one that avoids the problem you get into if you explicitly test for end-of-file on an interactive file descriptor causing your program to appear to hang. .IX Xref "eof end-of-file end of file" .PP .Vb 5 \& $on_a_tty = \-t STDIN && \-t STDOUT; \& sub prompt { print "yes? " if $on_a_tty } \& for ( prompt(); ; prompt() ) { \& # do something \& } .Ve .PP The condition expression of a \f(CW\*(C`for\*(C'\fR loop gets the same magic treatment of \&\f(CW\*(C`readline\*(C'\fR et al that the condition expression of a \f(CW\*(C`while\*(C'\fR loop gets. .SS "Foreach Loops" .IX Xref "for foreach" .IX Subsection "Foreach Loops" The \f(CW\*(C`foreach\*(C'\fR loop iterates over a normal list value and sets the scalar variable VAR to be each element of the list in turn. If the variable is preceded with the keyword \f(CW\*(C`my\*(C'\fR, then it is lexically scoped, and is therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with \f(CW\*(C`my\*(C'\fR, it uses that variable instead of the global one, but it's still localized to the loop. This implicit localization occurs \fIonly\fR for non C\-style loops. .IX Xref "my local" .PP The \f(CW\*(C`foreach\*(C'\fR keyword is actually a synonym for the \f(CW\*(C`for\*(C'\fR keyword, so you can use either. If VAR is omitted, \f(CW$_\fR is set to each value. .IX Xref "$_" .PP If any element of LIST is an lvalue, you can modify it by modifying VAR inside the loop. Conversely, if any element of LIST is NOT an lvalue, any attempt to modify that element will fail. In other words, the \f(CW\*(C`foreach\*(C'\fR loop index variable is an implicit alias for each item in the list that you're looping over. .IX Xref "alias" .PP If any part of LIST is an array, \f(CW\*(C`foreach\*(C'\fR will get very confused if you add or remove elements within the loop body, for example with \&\f(CW\*(C`splice\*(C'\fR. So don't do that. .IX Xref "splice" .PP \&\f(CW\*(C`foreach\*(C'\fR probably won't do what you expect if VAR is a tied or other special variable. Don't do that either. .PP As of Perl 5.22, there is an experimental variant of this loop that accepts a variable preceded by a backslash for VAR, in which case the items in the LIST must be references. The backslashed variable will become an alias to each referenced item in the LIST, which must be of the correct type. The variable needn't be a scalar in this case, and the backslash may be followed by \f(CW\*(C`my\*(C'\fR. To use this form, you must enable the \f(CW\*(C`refaliasing\*(C'\fR feature via \f(CW\*(C`use feature\*(C'\fR. (See feature. See also "Assigning to References" in perlref.) .PP As of Perl 5.36, you can iterate over multiple values at a time. You can only iterate with lexical scalars as the iterator variables \- unlike list assignment, it's not possible to use \f(CW\*(C`undef\*(C'\fR to signify a value that isn't wanted. This is a limitation of the current implementation, and might be changed in the future. .PP If the size of the LIST is not an exact multiple of the number of iterator variables, then on the last iteration the "excess" iterator variables are aliases to \f(CW\*(C`undef\*(C'\fR, as if the LIST had \f(CW\*(C`, undef\*(C'\fR appended as many times as needed for its length to become an exact multiple. This happens whether LIST is a literal LIST or an array \- ie arrays are not extended if their size is not a multiple of the iteration size, consistent with iterating an array one-at-a-time. As these padding elements are not lvalues, attempting to modify them will fail, consistent with the behaviour when iterating a list with literal \f(CW\*(C`undef\*(C'\fRs. If this is not the behaviour you desire, then before the loop starts either explicitly extend your array to be an exact multiple, or explicitly throw an exception. .PP Examples: .PP .Vb 1 \& for (@ary) { s/foo/bar/ } \& \& for my $elem (@elements) { \& $elem *= 2; \& } \& \& for $count (reverse(1..10), "BOOM") { \& print $count, "\en"; \& sleep(1); \& } \& \& for (1..15) { print "Merry Christmas\en"; } \& \& foreach $item (split(/:[\e\e\en:]*/, $ENV{TERMCAP})) { \& print "Item: $item\en"; \& } \& \& use feature "refaliasing"; \& no warnings "experimental::refaliasing"; \& foreach \emy %hash (@array_of_hash_references) { \& # do something with each %hash \& } \& \& foreach my ($foo, $bar, $baz) (@list) { \& # do something three\-at\-a\-time \& } \& \& foreach my ($key, $value) (%hash) { \& # iterate over the hash \& # The hash is immediately copied to a flat list before the loop \& # starts. The list contains copies of keys but aliases of values. \& # This is the same behaviour as for $var (%hash) {...} \& } .Ve .PP Here's how a C programmer might code up a particular algorithm in Perl: .PP .Vb 9 \& for (my $i = 0; $i < @ary1; $i++) { \& for (my $j = 0; $j < @ary2; $j++) { \& if ($ary1[$i] > $ary2[$j]) { \& last; # can\*(Aqt go to outer :\-( \& } \& $ary1[$i] += $ary2[$j]; \& } \& # this is where that last takes me \& } .Ve .PP Whereas here's how a Perl programmer more comfortable with the idiom might do it: .PP .Vb 6 \& OUTER: for my $wid (@ary1) { \& INNER: for my $jet (@ary2) { \& next OUTER if $wid > $jet; \& $wid += $jet; \& } \& } .Ve .PP See how much easier this is? It's cleaner, safer, and faster. It's cleaner because it's less noisy. It's safer because if code gets added between the inner and outer loops later on, the new code won't be accidentally executed. The \f(CW\*(C`next\*(C'\fR explicitly iterates the other loop rather than merely terminating the inner one. And it's faster because Perl executes a \f(CW\*(C`foreach\*(C'\fR statement more rapidly than it would the equivalent C\-style \f(CW\*(C`for\*(C'\fR loop. .PP Perceptive Perl hackers may have noticed that a \f(CW\*(C`for\*(C'\fR loop has a return value, and that this value can be captured by wrapping the loop in a \f(CW\*(C`do\*(C'\fR block. The reward for this discovery is this cautionary advice: The return value of a \f(CW\*(C`for\*(C'\fR loop is unspecified and may change without notice. Do not rely on it. .SS "Try Catch Exception Handling" .IX Xref "try catch finally" .IX Subsection "Try Catch Exception Handling" The \f(CW\*(C`try\*(C'\fR/\f(CW\*(C`catch\*(C'\fR syntax provides control flow relating to exception handling. The \f(CW\*(C`try\*(C'\fR keyword introduces a block which will be executed when it is encountered, and the \f(CW\*(C`catch\*(C'\fR block provides code to handle any exception that may be thrown by the first. .PP .Vb 9 \& try { \& my $x = call_a_function(); \& $x < 100 or die "Too big"; \& send_output($x); \& } \& catch ($e) { \& warn "Unable to output a value; $e"; \& } \& print "Finished\en"; .Ve .PP Here, the body of the \f(CW\*(C`catch\*(C'\fR block (i.e. the \f(CW\*(C`warn\*(C'\fR statement) will be executed if the initial block invokes the conditional \f(CW\*(C`die\*(C'\fR, or if either of the functions it invokes throws an uncaught exception. The \f(CW\*(C`catch\*(C'\fR block can inspect the \f(CW$e\fR lexical variable in this case to see what the exception was. If no exception was thrown then the \f(CW\*(C`catch\*(C'\fR block does not happen. In either case, execution will then continue from the following statement \- in this example the \f(CW\*(C`print\*(C'\fR. .PP The \f(CW\*(C`catch\*(C'\fR keyword must be immediately followed by a variable declaration in parentheses, which introduces a new variable visible to the body of the subsequent block. Inside the block this variable will contain the exception value that was thrown by the code in the \f(CW\*(C`try\*(C'\fR block. It is not necessary to use the \f(CW\*(C`my\*(C'\fR keyword to declare this variable; this is implied (similar as it is for subroutine signatures). .PP Both the \f(CW\*(C`try\*(C'\fR and the \f(CW\*(C`catch\*(C'\fR blocks are permitted to contain control-flow expressions, such as \f(CW\*(C`return\*(C'\fR, \f(CW\*(C`goto\*(C'\fR, or \f(CW\*(C`next\*(C'\fR/\f(CW\*(C`last\*(C'\fR/\f(CW\*(C`redo\*(C'\fR. In all cases they behave as expected without warnings. In particular, a \f(CW\*(C`return\*(C'\fR expression inside the \f(CW\*(C`try\*(C'\fR block will make its entire containing function return \- this is in contrast to its behaviour inside an \f(CW\*(C`eval\*(C'\fR block, where it would only make that block return. .PP Like other control-flow syntax, \f(CW\*(C`try\*(C'\fR and \f(CW\*(C`catch\*(C'\fR will yield the last evaluated value when placed as the final statement in a function or a \f(CW\*(C`do\*(C'\fR block. This permits the syntax to be used to create a value. In this case remember not to use the \f(CW\*(C`return\*(C'\fR expression, or that will cause the containing function to return. .PP .Vb 9 \& my $value = do { \& try { \& get_thing(@args); \& } \& catch ($e) { \& warn "Unable to get thing \- $e"; \& $DEFAULT_THING; \& } \& }; .Ve .PP As with other control-flow syntax, \f(CW\*(C`try\*(C'\fR blocks are not visible to \&\f(CWcaller()\fR (just as for example, \f(CW\*(C`while\*(C'\fR or \f(CW\*(C`foreach\*(C'\fR loops are not). Successive levels of the \f(CW\*(C`caller\*(C'\fR result can see subroutine calls and \&\f(CW\*(C`eval\*(C'\fR blocks, because those affect the way that \f(CW\*(C`return\*(C'\fR would work. Since \&\f(CW\*(C`try\*(C'\fR blocks do not intercept \f(CW\*(C`return\*(C'\fR, they are not of interest to \&\f(CW\*(C`caller\*(C'\fR. .PP The \f(CW\*(C`try\*(C'\fR and \f(CW\*(C`catch\*(C'\fR blocks may optionally be followed by a third block introduced by the \f(CW\*(C`finally\*(C'\fR keyword. This third block is executed after the rest of the construct has finished. .PP .Vb 9 \& try { \& call_a_function(); \& } \& catch ($e) { \& warn "Unable to call; $e"; \& } \& finally { \& print "Finished\en"; \& } .Ve .PP The \f(CW\*(C`finally\*(C'\fR block is equivalent to using a \f(CW\*(C`defer\*(C'\fR block and will be invoked in the same situations; whether the \f(CW\*(C`try\*(C'\fR block completes successfully, throws an exception, or transfers control elsewhere by using \&\f(CW\*(C`return\*(C'\fR, a loop control, or \f(CW\*(C`goto\*(C'\fR. .PP Unlike the \f(CW\*(C`try\*(C'\fR and \f(CW\*(C`catch\*(C'\fR blocks, a \f(CW\*(C`finally\*(C'\fR block is not permitted to \&\f(CW\*(C`return\*(C'\fR, \f(CW\*(C`goto\*(C'\fR or use any loop controls. The final expression value is ignored, and does not affect the return value of the containing function even if it is placed last in the function. .PP This syntax is currently experimental and must be enabled with \&\f(CW\*(C`use feature \*(Aqtry\*(Aq\*(C'\fR. It emits a warning in the \f(CW\*(C`experimental::try\*(C'\fR category. .SS "Basic BLOCKs" .IX Xref "block" .IX Subsection "Basic BLOCKs" A BLOCK by itself (labeled or not) is semantically equivalent to a loop that executes once. Thus you can use any of the loop control statements in it to leave or restart the block. (Note that this is \&\fINOT\fR true in \f(CW\*(C`eval{}\*(C'\fR, \f(CW\*(C`sub{}\*(C'\fR, or contrary to popular belief \&\f(CW\*(C`do{}\*(C'\fR blocks, which do \fINOT\fR count as loops.) The \f(CW\*(C`continue\*(C'\fR block is optional. .PP The BLOCK construct can be used to emulate case structures. .PP .Vb 6 \& SWITCH: { \& if (/^abc/) { $abc = 1; last SWITCH; } \& if (/^def/) { $def = 1; last SWITCH; } \& if (/^xyz/) { $xyz = 1; last SWITCH; } \& $nothing = 1; \& } .Ve .PP You'll also find that \f(CW\*(C`foreach\*(C'\fR loop used to create a topicalizer and a switch: .PP .Vb 7 \& SWITCH: \& for ($var) { \& if (/^abc/) { $abc = 1; last SWITCH; } \& if (/^def/) { $def = 1; last SWITCH; } \& if (/^xyz/) { $xyz = 1; last SWITCH; } \& $nothing = 1; \& } .Ve .PP Such constructs are quite frequently used, both because older versions of Perl had no official \f(CW\*(C`switch\*(C'\fR statement, and also because the new version described immediately below remains experimental and can sometimes be confusing. .SS "defer blocks" .IX Xref "defer" .IX Subsection "defer blocks" A block prefixed by the \f(CW\*(C`defer\*(C'\fR modifier provides a section of code which runs at a later time during scope exit. .PP A \f(CW\*(C`defer\*(C'\fR block can appear at any point where a regular block or other statement is permitted. If the flow of execution reaches this statement, the body of the block is stored for later, but not invoked immediately. When the flow of control leaves the containing block for any reason, this stored block is executed on the way past. It provides a means of deferring execution until a later time. This acts similarly to syntax provided by some other languages, often using keywords named \f(CW\*(C`try / finally\*(C'\fR. .PP This syntax is available if enabled by the \f(CW\*(C`defer\*(C'\fR named feature, and is currently experimental. If experimental warnings are enabled it will emit a warning when used. .PP .Vb 1 \& use feature \*(Aqdefer\*(Aq; \& \& { \& say "This happens first"; \& defer { say "This happens last"; } \& \& say "And this happens inbetween"; \& } .Ve .PP If multiple \f(CW\*(C`defer\*(C'\fR blocks are contained in a single scope, they are executed in LIFO order; the last one reached is the first one executed. .PP The code stored by the \f(CW\*(C`defer\*(C'\fR block will be invoked when control leaves its containing block due to regular fallthrough, explicit \f(CW\*(C`return\*(C'\fR, exceptions thrown by \f(CW\*(C`die\*(C'\fR or propagated by functions called by it, \f(CW\*(C`goto\*(C'\fR, or any of the loop control statements \f(CW\*(C`next\*(C'\fR, \f(CW\*(C`last\*(C'\fR or \f(CW\*(C`redo\*(C'\fR. .PP If the flow of control does not reach the \f(CW\*(C`defer\*(C'\fR statement itself then its body is not stored for later execution. (This is in direct contrast to the code provided by an \f(CW\*(C`END\*(C'\fR phaser block, which is always enqueued by the compiler, regardless of whether execution ever reached the line it was given on.) .PP .Vb 1 \& use feature \*(Aqdefer\*(Aq; \& \& { \& defer { say "This will run"; } \& return; \& defer { say "This will not"; } \& } .Ve .PP Exceptions thrown by code inside a \f(CW\*(C`defer\*(C'\fR block will propagate to the caller in the same way as any other exception thrown by normal code. .PP If the \f(CW\*(C`defer\*(C'\fR block is being executed due to a thrown exception and throws another one it is not specified what happens, beyond that the caller will definitely receive an exception. .PP Besides throwing an exception, a \f(CW\*(C`defer\*(C'\fR block is not permitted to otherwise alter the control flow of its surrounding code. In particular, it may not cause its containing function to \f(CW\*(C`return\*(C'\fR, nor may it \f(CW\*(C`goto\*(C'\fR a label, or control a containing loop using \f(CW\*(C`next\*(C'\fR, \f(CW\*(C`last\*(C'\fR or \f(CW\*(C`redo\*(C'\fR. These constructions are however, permitted entirely within the body of the \&\f(CW\*(C`defer\*(C'\fR. .PP .Vb 1 \& use feature \*(Aqdefer\*(Aq; \& \& { \& defer { \& foreach ( 1 .. 5 ) { \& last if $_ == 3; # this is permitted \& } \& } \& } \& \& { \& foreach ( 6 .. 10 ) { \& defer { \& last if $_ == 8; # this is not \& } \& } \& } .Ve .SS "Switch Statements" .IX Subsection "Switch Statements" .IX Xref "switch case given when default" .PP Starting from Perl 5.10.1 (well, 5.10.0, but it didn't work right), you can say .PP .Vb 1 \& use feature "switch"; .Ve .PP to enable an experimental switch feature. This is loosely based on an old version of a Raku proposal, but it no longer resembles the Raku construct. You also get the switch feature whenever you declare that your code prefers to run under a version of Perl between 5.10 and 5.34. For example: .PP .Vb 1 \& use v5.14; .Ve .PP Under the "switch" feature, Perl gains the experimental keywords \&\f(CW\*(C`given\*(C'\fR, \f(CW\*(C`when\*(C'\fR, \f(CW\*(C`default\*(C'\fR, \f(CW\*(C`continue\*(C'\fR, and \f(CW\*(C`break\*(C'\fR. Starting from Perl 5.16, one can prefix the switch keywords with \f(CW\*(C`CORE::\*(C'\fR to access the feature without a \f(CW\*(C`use feature\*(C'\fR statement. The keywords \f(CW\*(C`given\*(C'\fR and \&\f(CW\*(C`when\*(C'\fR are analogous to \f(CW\*(C`switch\*(C'\fR and \&\f(CW\*(C`case\*(C'\fR in other languages \-\- though \f(CW\*(C`continue\*(C'\fR is not \-\- so the code in the previous section could be rewritten as .PP .Vb 7 \& use v5.10.1; \& for ($var) { \& when (/^abc/) { $abc = 1 } \& when (/^def/) { $def = 1 } \& when (/^xyz/) { $xyz = 1 } \& default { $nothing = 1 } \& } .Ve .PP The \f(CW\*(C`foreach\*(C'\fR is the non-experimental way to set a topicalizer. If you wish to use the highly experimental \f(CW\*(C`given\*(C'\fR, that could be written like this: .PP .Vb 7 \& use v5.10.1; \& given ($var) { \& when (/^abc/) { $abc = 1 } \& when (/^def/) { $def = 1 } \& when (/^xyz/) { $xyz = 1 } \& default { $nothing = 1 } \& } .Ve .PP As of 5.14, that can also be written this way: .PP .Vb 7 \& use v5.14; \& for ($var) { \& $abc = 1 when /^abc/; \& $def = 1 when /^def/; \& $xyz = 1 when /^xyz/; \& default { $nothing = 1 } \& } .Ve .PP Or if you don't care to play it safe, like this: .PP .Vb 7 \& use v5.14; \& given ($var) { \& $abc = 1 when /^abc/; \& $def = 1 when /^def/; \& $xyz = 1 when /^xyz/; \& default { $nothing = 1 } \& } .Ve .PP The arguments to \f(CW\*(C`given\*(C'\fR and \f(CW\*(C`when\*(C'\fR are in scalar context, and \f(CW\*(C`given\*(C'\fR assigns the \f(CW$_\fR variable its topic value. .PP Exactly what the \fIEXPR\fR argument to \f(CW\*(C`when\*(C'\fR does is hard to describe precisely, but in general, it tries to guess what you want done. Sometimes it is interpreted as \f(CW\*(C`$_ ~~ \fR\f(CIEXPR\fR\f(CW\*(C'\fR, and sometimes it is not. It also behaves differently when lexically enclosed by a \f(CW\*(C`given\*(C'\fR block than it does when dynamically enclosed by a \f(CW\*(C`foreach\*(C'\fR loop. The rules are far too difficult to understand to be described here. See "Experimental Details on given and when" later on. .PP Due to an unfortunate bug in how \f(CW\*(C`given\*(C'\fR was implemented between Perl 5.10 and 5.16, under those implementations the version of \f(CW$_\fR governed by \&\f(CW\*(C`given\*(C'\fR is merely a lexically scoped copy of the original, not a dynamically scoped alias to the original, as it would be if it were a \&\f(CW\*(C`foreach\*(C'\fR or under both the original and the current Raku language specification. This bug was fixed in Perl 5.18 (and lexicalized \f(CW$_\fR itself was removed in Perl 5.24). .PP If your code still needs to run on older versions, stick to \f(CW\*(C`foreach\*(C'\fR for your topicalizer and you will be less unhappy. .SS Goto .IX Xref "goto" .IX Subsection "Goto" Although not for the faint of heart, Perl does support a \f(CW\*(C`goto\*(C'\fR statement. There are three forms: \f(CW\*(C`goto\*(C'\fR\-LABEL, \f(CW\*(C`goto\*(C'\fR\-EXPR, and \&\f(CW\*(C`goto\*(C'\fR\-&NAME. A loop's LABEL is not actually a valid target for a \f(CW\*(C`goto\*(C'\fR; it's just the name of the loop. .PP The \f(CW\*(C`goto\*(C'\fR\-LABEL form finds the statement labeled with LABEL and resumes execution there. It may not be used to go into any construct that requires initialization, such as a subroutine or a \f(CW\*(C`foreach\*(C'\fR loop. It also can't be used to go into a construct that is optimized away. It can be used to go almost anywhere else within the dynamic scope, including out of subroutines, but it's usually better to use some other construct such as \f(CW\*(C`last\*(C'\fR or \f(CW\*(C`die\*(C'\fR. The author of Perl has never felt the need to use this form of \f(CW\*(C`goto\*(C'\fR (in Perl, that is\-\-C is another matter). .PP The \f(CW\*(C`goto\*(C'\fR\-EXPR form expects a label name, whose scope will be resolved dynamically. This allows for computed \f(CW\*(C`goto\*(C'\fRs per FORTRAN, but isn't necessarily recommended if you're optimizing for maintainability: .PP .Vb 1 \& goto(("FOO", "BAR", "GLARCH")[$i]); .Ve .PP The \f(CW\*(C`goto\*(C'\fR\-&NAME form is highly magical, and substitutes a call to the named subroutine for the currently running subroutine. This is used by \&\f(CWAUTOLOAD()\fR subroutines that wish to load another subroutine and then pretend that the other subroutine had been called in the first place (except that any modifications to \f(CW@_\fR in the current subroutine are propagated to the other subroutine.) After the \f(CW\*(C`goto\*(C'\fR, not even \f(CWcaller()\fR will be able to tell that this routine was called first. .PP In almost all cases like this, it's usually a far, far better idea to use the structured control flow mechanisms of \f(CW\*(C`next\*(C'\fR, \f(CW\*(C`last\*(C'\fR, or \f(CW\*(C`redo\*(C'\fR instead of resorting to a \f(CW\*(C`goto\*(C'\fR. For certain applications, the catch and throw pair of \&\f(CW\*(C`eval{}\*(C'\fR and \fBdie()\fR for exception processing can also be a prudent approach. .SS "The Ellipsis Statement" .IX Xref "... ... statement ellipsis operator elliptical statement unimplemented statement unimplemented operator yada-yada yada-yada operator ... operator whatever operator triple-dot operator" .IX Subsection "The Ellipsis Statement" Beginning in Perl 5.12, Perl accepts an ellipsis, "\f(CW\*(C`...\*(C'\fR", as a placeholder for code that you haven't implemented yet. When Perl 5.12 or later encounters an ellipsis statement, it parses this without error, but if and when you should actually try to execute it, Perl throws an exception with the text \f(CW\*(C`Unimplemented\*(C'\fR: .PP .Vb 6 \& use v5.12; \& sub unimplemented { ... } \& eval { unimplemented() }; \& if ($@ =~ /^Unimplemented at /) { \& say "I found an ellipsis!"; \& } .Ve .PP You can only use the elliptical statement to stand in for a complete statement. Syntactically, "\f(CW\*(C`...;\*(C'\fR" is a complete statement, but, as with other kinds of semicolon-terminated statement, the semicolon may be omitted if "\f(CW\*(C`...\*(C'\fR" appears immediately before a closing brace. These examples show how the ellipsis works: .PP .Vb 10 \& use v5.12; \& { ... } \& sub foo { ... } \& ...; \& eval { ... }; \& sub somemeth { \& my $self = shift; \& ...; \& } \& $x = do { \& my $n; \& ...; \& say "Hurrah!"; \& $n; \& }; .Ve .PP The elliptical statement cannot stand in for an expression that is part of a larger statement. These examples of attempts to use an ellipsis are syntax errors: .PP .Vb 1 \& use v5.12; \& \& print ...; \& open(my $fh, ">", "/dev/passwd") or ...; \& if ($condition && ... ) { say "Howdy" }; \& ... if $a > $b; \& say "Cromulent" if ...; \& $flub = 5 + ...; .Ve .PP There are some cases where Perl can't immediately tell the difference between an expression and a statement. For instance, the syntax for a block and an anonymous hash reference constructor look the same unless there's something in the braces to give Perl a hint. The ellipsis is a syntax error if Perl doesn't guess that the \f(CW\*(C`{ ... }\*(C'\fR is a block. Inside your block, you can use a \f(CW\*(C`;\*(C'\fR before the ellipsis to denote that the \&\f(CW\*(C`{ ... }\*(C'\fR is a block and not a hash reference constructor. .PP Note: Some folks colloquially refer to this bit of punctuation as a "yada-yada" or "triple-dot", but its true name is actually an ellipsis. .SS "PODs: Embedded Documentation" .IX Xref "POD documentation" .IX Subsection "PODs: Embedded Documentation" Perl has a mechanism for intermixing documentation with source code. While it's expecting the beginning of a new statement, if the compiler encounters a line that begins with an equal sign and a word, like this .PP .Vb 1 \& =head1 Here There Be Pods! .Ve .PP Then that text and all remaining text up through and including a line beginning with \f(CW\*(C`=cut\*(C'\fR will be ignored. The format of the intervening text is described in perlpod. .PP This allows you to intermix your source code and your documentation text freely, as in .PP .Vb 1 \& =item snazzle($) \& \& The snazzle() function will behave in the most spectacular \& form that you can possibly imagine, not even excepting \& cybernetic pyrotechnics. \& \& =cut back to the compiler, nuff of this pod stuff! \& \& sub snazzle($) { \& my $thingie = shift; \& ......... \& } .Ve .PP Note that pod translators should look at only paragraphs beginning with a pod directive (it makes parsing easier), whereas the compiler actually knows to look for pod escapes even in the middle of a paragraph. This means that the following secret stuff will be ignored by both the compiler and the translators. .PP .Vb 5 \& $a=3; \& =secret stuff \& warn "Neither POD nor CODE!?" \& =cut back \& print "got $a\en"; .Ve .PP You probably shouldn't rely upon the \f(CWwarn()\fR being podded out forever. Not all pod translators are well-behaved in this regard, and perhaps the compiler will become pickier. .PP One may also use pod directives to quickly comment out a section of code. .SS "Plain Old Comments (Not!)" .IX Xref "comment line # preprocessor eval" .IX Subsection "Plain Old Comments (Not!)" Perl can process line directives, much like the C preprocessor. Using this, one can control Perl's idea of filenames and line numbers in error or warning messages (especially for strings that are processed with \f(CWeval()\fR). The syntax for this mechanism is almost the same as for most C preprocessors: it matches the regular expression .PP .Vb 5 \& # example: \*(Aq# line 42 "new_filename.plx"\*(Aq \& /^\e# \es* \& line \es+ (\ed+) \es* \& (?:\es("?)([^"]+)\eg2)? \es* \& $/x .Ve .PP with \f(CW$1\fR being the line number for the next line, and \f(CW$3\fR being the optional filename (specified with or without quotes). Note that no whitespace may precede the \f(CW\*(C`#\*(C'\fR, unlike modern C preprocessors. .PP There is a fairly obvious gotcha included with the line directive: Debuggers and profilers will only show the last source line to appear at a particular line number in a given file. Care should be taken not to cause line number collisions in code you'd like to debug later. .PP Here are some examples that you should be able to type into your command shell: .PP .Vb 6 \& % perl \& # line 200 "bzzzt" \& # the \*(Aq#\*(Aq on the previous line must be the first char on line \& die \*(Aqfoo\*(Aq; \& _\|_END_\|_ \& foo at bzzzt line 201. \& \& % perl \& # line 200 "bzzzt" \& eval qq[\en#line 2001 ""\endie \*(Aqfoo\*(Aq]; print $@; \& _\|_END_\|_ \& foo at \- line 2001. \& \& % perl \& eval qq[\en#line 200 "foo bar"\endie \*(Aqfoo\*(Aq]; print $@; \& _\|_END_\|_ \& foo at foo bar line 200. \& \& % perl \& # line 345 "goop" \& eval "\en#line " . _\|_LINE_\|_ . \*(Aq "\*(Aq . _\|_FILE_\|_ ."\e"\endie \*(Aqfoo\*(Aq"; \& print $@; \& _\|_END_\|_ \& foo at goop line 345. .Ve .SS "Experimental Details on given and when" .IX Subsection "Experimental Details on given and when" As previously mentioned, the "switch" feature is considered highly experimental (it is also scheduled to be removed in perl 5.42.0); it is subject to change with little notice. In particular, \&\f(CW\*(C`when\*(C'\fR has tricky behaviours that are expected to change to become less tricky in the future. Do not rely upon its current (mis)implementation. Before Perl 5.18, \f(CW\*(C`given\*(C'\fR also had tricky behaviours that you should still beware of if your code must run on older versions of Perl. .PP Here is a longer example of \f(CW\*(C`given\*(C'\fR: .PP .Vb 10 \& use feature ":5.10"; \& given ($foo) { \& when (undef) { \& say \*(Aq$foo is undefined\*(Aq; \& } \& when ("foo") { \& say \*(Aq$foo is the string "foo"\*(Aq; \& } \& when ([1,3,5,7,9]) { \& say \*(Aq$foo is an odd digit\*(Aq; \& continue; # Fall through \& } \& when ($_ < 100) { \& say \*(Aq$foo is numerically less than 100\*(Aq; \& } \& when (\e&complicated_check) { \& say \*(Aqa complicated check for $foo is true\*(Aq; \& } \& default { \& die q(I don\*(Aqt know what to do with $foo); \& } \& } .Ve .PP Before Perl 5.18, \f(CWgiven(EXPR)\fR assigned the value of \fIEXPR\fR to merely a lexically scoped \fR\f(BIcopy\fR\fI\fR (!) of \f(CW$_\fR, not a dynamically scoped alias the way \f(CW\*(C`foreach\*(C'\fR does. That made it similar to .PP .Vb 1 \& do { my $_ = EXPR; ... } .Ve .PP except that the block was automatically broken out of by a successful \&\f(CW\*(C`when\*(C'\fR or an explicit \f(CW\*(C`break\*(C'\fR. Because it was only a copy, and because it was only lexically scoped, not dynamically scoped, you could not do the things with it that you are used to in a \f(CW\*(C`foreach\*(C'\fR loop. In particular, it did not work for arbitrary function calls if those functions might try to access \f(CW$_\fR. Best stick to \f(CW\*(C`foreach\*(C'\fR for that. .PP Most of the power comes from the implicit smartmatching that can sometimes apply. Most of the time, \f(CWwhen(EXPR)\fR is treated as an implicit smartmatch of \f(CW$_\fR, that is, \f(CW\*(C`$_ ~~ EXPR\*(C'\fR. (See "Smartmatch Operator" in perlop for more information on smartmatching.) But when \fIEXPR\fR is one of the 10 exceptional cases (or things like them) listed below, it is used directly as a boolean. .IP 1. 4 .IX Item "1." A user-defined subroutine call or a method invocation. .IP 2. 4 .IX Item "2." A regular expression match in the form of \f(CW\*(C`/REGEX/\*(C'\fR, \f(CW\*(C`$foo =~ /REGEX/\*(C'\fR, or \f(CW\*(C`$foo =~ EXPR\*(C'\fR. Also, a negated regular expression match in the form \f(CW\*(C`!/REGEX/\*(C'\fR, \f(CW\*(C`$foo !~ /REGEX/\*(C'\fR, or \f(CW\*(C`$foo !~ EXPR\*(C'\fR. .IP 3. 4 .IX Item "3." A smart match that uses an explicit \f(CW\*(C`~~\*(C'\fR operator, such as \f(CW\*(C`EXPR ~~ EXPR\*(C'\fR. .Sp \&\fBNOTE:\fR You will often have to use \f(CW\*(C`$c ~~ $_\*(C'\fR because the default case uses \f(CW\*(C`$_ ~~ $c\*(C'\fR , which is frequently the opposite of what you want. .IP 4. 4 .IX Item "4." A boolean comparison operator such as \f(CW\*(C`$_ < 10\*(C'\fR or \f(CW\*(C`$x eq "abc"\*(C'\fR. The relational operators that this applies to are the six numeric comparisons (\f(CW\*(C`<\*(C'\fR, \f(CW\*(C`>\*(C'\fR, \f(CW\*(C`<=\*(C'\fR, \f(CW\*(C`>=\*(C'\fR, \f(CW\*(C`==\*(C'\fR, and \f(CW\*(C`!=\*(C'\fR), and the six string comparisons (\f(CW\*(C`lt\*(C'\fR, \f(CW\*(C`gt\*(C'\fR, \f(CW\*(C`le\*(C'\fR, \f(CW\*(C`ge\*(C'\fR, \f(CW\*(C`eq\*(C'\fR, and \f(CW\*(C`ne\*(C'\fR). .IP 5. 4 .IX Item "5." At least the three builtin functions \f(CWdefined(...)\fR, \f(CWexists(...)\fR, and \&\f(CWeof(...)\fR. We might someday add more of these later if we think of them. .IP 6. 4 .IX Item "6." A negated expression, whether \f(CW\*(C`!(EXPR)\*(C'\fR or \f(CWnot(EXPR)\fR, or a logical exclusive-or, \f(CW\*(C`(EXPR1) xor (EXPR2)\*(C'\fR. The bitwise versions (\f(CW\*(C`~\*(C'\fR and \f(CW\*(C`^\*(C'\fR) are not included. .IP 7. 4 .IX Item "7." A filetest operator, with exactly 4 exceptions: \f(CW\*(C`\-s\*(C'\fR, \f(CW\*(C`\-M\*(C'\fR, \f(CW\*(C`\-A\*(C'\fR, and \&\f(CW\*(C`\-C\*(C'\fR, as these return numerical values, not boolean ones. The \f(CW\*(C`\-z\*(C'\fR filetest operator is not included in the exception list. .IP 8. 4 .IX Item "8." The \f(CW\*(C`..\*(C'\fR and \f(CW\*(C`...\*(C'\fR flip-flop operators. Note that the \f(CW\*(C`...\*(C'\fR flip-flop operator is completely different from the \f(CW\*(C`...\*(C'\fR elliptical statement just described. .PP In those 8 cases above, the value of EXPR is used directly as a boolean, so no smartmatching is done. You may think of \f(CW\*(C`when\*(C'\fR as a smartsmartmatch. .PP Furthermore, Perl inspects the operands of logical operators to decide whether to use smartmatching for each one by applying the above test to the operands: .IP 9. 4 .IX Item "9." If EXPR is \f(CW\*(C`EXPR1 && EXPR2\*(C'\fR or \f(CW\*(C`EXPR1 and EXPR2\*(C'\fR, the test is applied \&\fIrecursively\fR to both EXPR1 and EXPR2. Only if \fIboth\fR operands also pass the test, \fIrecursively\fR, will the expression be treated as boolean. Otherwise, smartmatching is used. .IP 10. 4 .IX Item "10." If EXPR is \f(CW\*(C`EXPR1 || EXPR2\*(C'\fR, \f(CW\*(C`EXPR1 // EXPR2\*(C'\fR, or \f(CW\*(C`EXPR1 or EXPR2\*(C'\fR, the test is applied \fIrecursively\fR to EXPR1 only (which might itself be a higher-precedence AND operator, for example, and thus subject to the previous rule), not to EXPR2. If EXPR1 is to use smartmatching, then EXPR2 also does so, no matter what EXPR2 contains. But if EXPR2 does not get to use smartmatching, then the second argument will not be either. This is quite different from the \f(CW\*(C`&&\*(C'\fR case just described, so be careful. .PP These rules are complicated, but the goal is for them to do what you want (even if you don't quite understand why they are doing it). For example: .PP .Vb 1 \& when (/^\ed+$/ && $_ < 75) { ... } .Ve .PP will be treated as a boolean match because the rules say both a regex match and an explicit test on \f(CW$_\fR will be treated as boolean. .PP Also: .PP .Vb 1 \& when ([qw(foo bar)] && /baz/) { ... } .Ve .PP will use smartmatching because only \fIone\fR of the operands is a boolean: the other uses smartmatching, and that wins. .PP Further: .PP .Vb 1 \& when ([qw(foo bar)] || /^baz/) { ... } .Ve .PP will use smart matching (only the first operand is considered), whereas .PP .Vb 1 \& when (/^baz/ || [qw(foo bar)]) { ... } .Ve .PP will test only the regex, which causes both operands to be treated as boolean. Watch out for this one, then, because an arrayref is always a true value, which makes it effectively redundant. Not a good idea. .PP Tautologous boolean operators are still going to be optimized away. Don't be tempted to write .PP .Vb 1 \& when ("foo" or "bar") { ... } .Ve .PP This will optimize down to \f(CW"foo"\fR, so \f(CW"bar"\fR will never be considered (even though the rules say to use a smartmatch on \f(CW"foo"\fR). For an alternation like this, an array ref will work, because this will instigate smartmatching: .PP .Vb 1 \& when ([qw(foo bar)] { ... } .Ve .PP This is somewhat equivalent to the C\-style switch statement's fallthrough functionality (not to be confused with \fIPerl's\fR fallthrough functionality\-\-see below), wherein the same block is used for several \&\f(CW\*(C`case\*(C'\fR statements. .PP Another useful shortcut is that, if you use a literal array or hash as the argument to \f(CW\*(C`given\*(C'\fR, it is turned into a reference. So \f(CWgiven(@foo)\fR is the same as \f(CWgiven(\e@foo)\fR, for example. .PP \&\f(CW\*(C`default\*(C'\fR behaves exactly like \f(CW\*(C`when(1 == 1)\*(C'\fR, which is to say that it always matches. .PP \fIBreaking out\fR .IX Subsection "Breaking out" .PP You can use the \f(CW\*(C`break\*(C'\fR keyword to break out of the enclosing \&\f(CW\*(C`given\*(C'\fR block. Every \f(CW\*(C`when\*(C'\fR block is implicitly ended with a \f(CW\*(C`break\*(C'\fR. .PP \fIFall-through\fR .IX Subsection "Fall-through" .PP You can use the \f(CW\*(C`continue\*(C'\fR keyword to fall through from one case to the next immediate \f(CW\*(C`when\*(C'\fR or \f(CW\*(C`default\*(C'\fR: .PP .Vb 5 \& given($foo) { \& when (/x/) { say \*(Aq$foo contains an x\*(Aq; continue } \& when (/y/) { say \*(Aq$foo contains a y\*(Aq } \& default { say \*(Aq$foo does not contain a y\*(Aq } \& } .Ve .PP \fIReturn value\fR .IX Subsection "Return value" .PP When a \f(CW\*(C`given\*(C'\fR statement is also a valid expression (for example, when it's the last statement of a block), it evaluates to: .IP \(bu 4 An empty list as soon as an explicit \f(CW\*(C`break\*(C'\fR is encountered. .IP \(bu 4 The value of the last evaluated expression of the successful \&\f(CW\*(C`when\*(C'\fR/\f(CW\*(C`default\*(C'\fR clause, if there happens to be one. .IP \(bu 4 The value of the last evaluated expression of the \f(CW\*(C`given\*(C'\fR block if no condition is true. .PP In both last cases, the last expression is evaluated in the context that was applied to the \f(CW\*(C`given\*(C'\fR block. .PP Note that, unlike \f(CW\*(C`if\*(C'\fR and \f(CW\*(C`unless\*(C'\fR, failed \f(CW\*(C`when\*(C'\fR statements always evaluate to an empty list. .PP .Vb 8 \& my $price = do { \& given ($item) { \& when (["pear", "apple"]) { 1 } \& break when "vote"; # My vote cannot be bought \& 1e10 when /Mona Lisa/; \& "unknown"; \& } \& }; .Ve .PP Currently, \f(CW\*(C`given\*(C'\fR blocks can't always be used as proper expressions. This may be addressed in a future version of Perl. .PP \fISwitching in a loop\fR .IX Subsection "Switching in a loop" .PP Instead of using \f(CWgiven()\fR, you can use a \f(CWforeach()\fR loop. For example, here's one way to count how many times a particular string occurs in an array: .PP .Vb 6 \& use v5.10.1; \& my $count = 0; \& for (@array) { \& when ("foo") { ++$count } \& } \& print "\e@array contains $count copies of \*(Aqfoo\*(Aq\en"; .Ve .PP Or in a more recent version: .PP .Vb 6 \& use v5.14; \& my $count = 0; \& for (@array) { \& ++$count when "foo"; \& } \& print "\e@array contains $count copies of \*(Aqfoo\*(Aq\en"; .Ve .PP At the end of all \f(CW\*(C`when\*(C'\fR blocks, there is an implicit \f(CW\*(C`next\*(C'\fR. You can override that with an explicit \f(CW\*(C`last\*(C'\fR if you're interested in only the first match alone. .PP This doesn't work if you explicitly specify a loop variable, as in \f(CW\*(C`for $item (@array)\*(C'\fR. You have to use the default variable \f(CW$_\fR. .PP \fIDifferences from Raku\fR .IX Subsection "Differences from Raku" .PP The Perl 5 smartmatch and \f(CW\*(C`given\*(C'\fR/\f(CW\*(C`when\*(C'\fR constructs are not compatible with their Raku analogues. The most visible difference and least important difference is that, in Perl 5, parentheses are required around the argument to \f(CWgiven()\fR and \f(CWwhen()\fR (except when this last one is used as a statement modifier). Parentheses in Raku are always optional in a control construct such as \f(CWif()\fR, \f(CWwhile()\fR, or \f(CWwhen()\fR; they can't be made optional in Perl 5 without a great deal of potential confusion, because Perl 5 would parse the expression .PP .Vb 3 \& given $foo { \& ... \& } .Ve .PP as though the argument to \f(CW\*(C`given\*(C'\fR were an element of the hash \&\f(CW%foo\fR, interpreting the braces as hash-element syntax. .PP However, their are many, many other differences. For example, this works in Perl 5: .PP .Vb 2 \& use v5.12; \& my @primary = ("red", "blue", "green"); \& \& if (@primary ~~ "red") { \& say "primary smartmatches red"; \& } \& \& if ("red" ~~ @primary) { \& say "red smartmatches primary"; \& } \& \& say "that\*(Aqs all, folks!"; .Ve .PP But it doesn't work at all in Raku. Instead, you should use the (parallelizable) \f(CW\*(C`any\*(C'\fR operator: .PP .Vb 3 \& if any(@primary) eq "red" { \& say "primary smartmatches red"; \& } \& \& if "red" eq any(@primary) { \& say "red smartmatches primary"; \& } .Ve .PP The table of smartmatches in "Smartmatch Operator" in perlop is not identical to that proposed by the Raku specification, mainly due to differences between Raku's and Perl 5's data models, but also because the Raku spec has changed since Perl 5 rushed into early adoption. .PP In Raku, \f(CWwhen()\fR will always do an implicit smartmatch with its argument, while in Perl 5 it is convenient (albeit potentially confusing) to suppress this implicit smartmatch in various rather loosely-defined situations, as roughly outlined above. (The difference is largely because Perl 5 does not have, even internally, a boolean type.)