.\" Automatically generated by Pod::Man 4.09 (Pod::Simple 3.35)
.\"
.\" 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
..
.\" Set up some character translations and predefined strings.  \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote.  \*(C+ will
.\" give a nicer C++.  Capital omega is used to do unbreakable dashes and
.\" therefore won't be available.  \*(C` and \*(C' expand to `' in nroff,
.\" nothing in troff, for use with C<>.
.tr \(*W-
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
.    ds -- \(*W-
.    ds PI pi
.    if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
.    if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\"  diablo 12 pitch
.    ds L" ""
.    ds R" ""
.    ds C` ""
.    ds C' ""
'br\}
.el\{\
.    ds -- \|\(em\|
.    ds PI \(*p
.    ds L" ``
.    ds R" ''
.    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
..
.if !\nF .nr F 0
.if \nF>0 \{\
.    de IX
.    tm Index:\\$1\t\\n%\t"\\$2"
..
.    if !\nF==2 \{\
.        nr % 0
.        nr F 2
.    \}
.\}
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear.  Run.  Save yourself.  No user-serviceable parts.
.    \" fudge factors for nroff and troff
.if n \{\
.    ds #H 0
.    ds #V .8m
.    ds #F .3m
.    ds #[ \f1
.    ds #] \fP
.\}
.if t \{\
.    ds #H ((1u-(\\\\n(.fu%2u))*.13m)
.    ds #V .6m
.    ds #F 0
.    ds #[ \&
.    ds #] \&
.\}
.    \" simple accents for nroff and troff
.if n \{\
.    ds ' \&
.    ds ` \&
.    ds ^ \&
.    ds , \&
.    ds ~ ~
.    ds /
.\}
.if t \{\
.    ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
.    ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
.    ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
.    ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
.    ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
.    ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
.    \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
.    \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
.    \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
.    ds : e
.    ds 8 ss
.    ds o a
.    ds d- d\h'-1'\(ga
.    ds D- D\h'-1'\(hy
.    ds th \o'bp'
.    ds Th \o'LP'
.    ds ae ae
.    ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ========================================================================
.\"
.IX Title "PERLSYN 1"
.TH PERLSYN 1 "2018-03-23" "perl v5.26.3" "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 \fB\s-1DWIM\s0\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(CW\*(C`my()\*(C'\fR,
\&\f(CW\*(C`state()\*(C'\fR, or \f(CW\*(C`our()\*(C'\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 "Truth and Falsehood"
.IX Xref "truth falsehood true false ! not negation 0"
.IX Subsection "Truth and Falsehood"
The number 0, the strings \f(CW\*(Aq0\*(Aq\fR and \f(CW""\fR, the empty list \f(CW\*(C`()\*(C'\fR, and
\&\f(CW\*(C`undef\*(C'\fR are all false in a boolean context.  All other values are true.
Negation of a true value by \f(CW\*(C`!\*(C'\fR or \f(CW\*(C`not\*(C'\fR returns a special false value.
When evaluated as a string it is treated as \f(CW""\fR, but as a number, it
is treated as 0.  Most Perl operators
that return true or false behave this way.
.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 \fI\s-1SINGLE\s0\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 \*(L"condition\*(R".
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).
.PP
.Vb 2
\&    print "Basset hounds got long ears" if length $ear >= 10;
\&    go_outside() and play() unless $is_raining;
.Ve
.PP
The \f(CW\*(C`for(each)\*(C'\fR modifier is an iterator: it executes the statement once
for each item in the \s-1LIST\s0 (with \f(CW$_\fR aliased to each item in turn).
.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.
\&\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 = <STDIN>;
\&        ...
\&    } until !defined($line) || $line eq ".\en"
.Ve
.PP
See \*(L"do\*(R" in perlfunc.  Note also that the loop control statements described
later will \fI\s-1NOT\s0\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
\&\fB\s-1NOTE:\s0\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`$_ ~~ \f(CIEXPR\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 \*(L"Switch Statements\*(R" 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 \s-1BLOCK.\s0
.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
The experimental \f(CW\*(C`given\*(C'\fR statement is \fInot automatically enabled\fR; see
\&\*(L"Switch Statements\*(R" 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 \s-1LABEL\s0 is optional, and if present, consists of an identifier followed
by a colon.  The \s-1LABEL\s0 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 \s-1LABEL\s0 is omitted, the loop control statement
refers to the innermost enclosing loop.  This may include dynamically
looking back your call-stack at run time to find the \s-1LABEL.\s0  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 there is a \f(CW\*(C`continue\*(C'\fR \s-1BLOCK,\s0 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 preceding 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
\&\*(L"PL_keyword_plugin\*(R" 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 (<STDIN>) {
\&        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 (<STDIN>) {
\&        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 = <ARGV>)) {
\&        chomp($line);
\&        if ($line =~ s/\e\e$//) {
\&            $line .= <ARGV>;
\&            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 \*(L"Basic BLOCKs\*(R".
.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).
.IX Xref "my"
.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(); <STDIN>; prompt() ) {
\&        # do something
\&    }
.Ve
.PP
Using \f(CW\*(C`readline\*(C'\fR (or the operator form, \f(CW\*(C`<EXPR>\*(C'\fR) as the
conditional of a \f(CW\*(C`for\*(C'\fR loop is shorthand for the following.  This
behaviour is the same as a \f(CW\*(C`while\*(C'\fR loop conditional.
.IX Xref "readline <>"
.PP
.Vb 3
\&    for ( prompt(); defined( $_ = <STDIN> ); prompt() ) {
\&        # do something
\&    }
.Ve
.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 \s-1VAR\s0 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 in a \f(CW\*(C`foreach\*(C'\fR
loop.
.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 \s-1VAR\s0 is omitted, \f(CW$_\fR is set to each value.
.IX Xref "$_"
.PP
If any element of \s-1LIST\s0 is an lvalue, you can modify it by modifying
\&\s-1VAR\s0 inside the loop.  Conversely, if any element of \s-1LIST\s0 is \s-1NOT\s0 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 \s-1LIST\s0 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 \s-1VAR\s0 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 \s-1VAR,\s0 in which case the items in the
\&\s-1LIST\s0 must be references.  The backslashed variable will become an alias
to each referenced item in the \s-1LIST,\s0 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 \*(L"Assigning
to References\*(R" in perlref.)
.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 which each %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 \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 "Basic BLOCKs"
.IX Xref "block"
.IX Subsection "Basic BLOCKs"
A \s-1BLOCK\s0 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
\&\fI\s-1NOT\s0\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 \fI\s-1NOT\s0\fR count as loops.)  The \f(CW\*(C`continue\*(C'\fR
block is optional.
.PP
The \s-1BLOCK\s0 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 "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 Perl 6 proposal, but it no longer resembles the Perl 6
construct.   You also get the switch feature whenever you declare that your
code prefers to run under a version of Perl that is 5.10 or later.  For
example:
.PP
.Vb 1
\&    use v5.14;
.Ve
.PP
Under the \*(L"switch\*(R" 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 \fI\s-1EXPR\s0\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`$_ ~~ \f(CIEXPR\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 \*(L"Experimental Details
on given and when\*(R" 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 Perl 6 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 \s-1LABEL\s0 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 \s-1LABEL\s0 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 \s-1FORTRAN,\s0 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(CW\*(C`AUTOLOAD()\*(C'\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(CW\*(C`caller()\*(C'\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 \fIdie()\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.  This form of
ellipsis, the unimplemented statement, should not be confused with the
binary flip-flop \f(CW\*(C`...\*(C'\fR operator.  One is a statement and the other an
operator.  (Perl doesn't usually confuse them because usually Perl can tell
whether it wants an operator or a statement, but see below for exceptions.)
.PP
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.  These examples of 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, since the \f(CW\*(C`...\*(C'\fR is also the three-dot
version of the flip-flop operator (see \*(L"Range Operators\*(R" in perlop).
.PP
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" };
.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.  In that
case, it doesn't think the \f(CW\*(C`...\*(C'\fR is an ellipsis because it's expecting an
expression instead of a statement:
.PP
.Vb 1
\&    @transformed = map { ... } @input;    # syntax error
.Ve
.PP
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.  Now the ellipsis
works:
.PP
.Vb 1
\&    @transformed = map {; ... } @input;   # \*(Aq;\*(Aq disambiguates
.Ve
.PP
Note: Some folks colloquially refer to this bit of punctuation as a
\&\*(L"yada-yada\*(R" or \*(L"triple-dot\*(R", 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(CW\*(C`warn()\*(C'\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(CW\*(C`eval()\*(C'\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 \*(L"switch\*(R" feature is considered highly
experimental; 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(CW\*(C`given(EXPR)\*(C'\fR assigned the value of \fI\s-1EXPR\s0\fR to
merely a lexically scoped \fI\f(BIcopy\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(CW\*(C`when(EXPR)\*(C'\fR is treated as an
implicit smartmatch of \f(CW$_\fR, that is, \f(CW\*(C`$_ ~~ EXPR\*(C'\fR.  (See
\&\*(L"Smartmatch Operator\*(R" in perlop for more information on smartmatching.)
But when \fI\s-1EXPR\s0\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
\&\fB\s-1NOTE:\s0\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 frequentlythe 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(CW\*(C`defined(...)\*(C'\fR, \f(CW\*(C`exists(...)\*(C'\fR, and
\&\f(CW\*(C`eof(...)\*(C'\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(CW\*(C`not(EXPR)\*(C'\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 \s-1EXPR\s0 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 \s-1EXPR\s0 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 \s-1EXPR1\s0 and \s-1EXPR2.\s0
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 \s-1EXPR\s0 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 \s-1EXPR1\s0 only (which might itself be a
higher-precedence \s-1AND\s0 operator, for example, and thus subject to the
previous rule), not to \s-1EXPR2.\s0  If \s-1EXPR1\s0 is to use smartmatching, then \s-1EXPR2\s0
also does so, no matter what \s-1EXPR2\s0 contains.  But if \s-1EXPR2\s0 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(CW\*(C`given(@foo)\*(C'\fR is
the same as \f(CW\*(C`given(\e@foo)\*(C'\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(CW\*(C`given()\*(C'\fR, you can use a \f(CW\*(C`foreach()\*(C'\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 Perl 6\fR
.IX Subsection "Differences from Perl 6"
.PP
The Perl 5 smartmatch and \f(CW\*(C`given\*(C'\fR/\f(CW\*(C`when\*(C'\fR constructs are not compatible
with their Perl 6 analogues.  The most visible difference and least
important difference is that, in Perl 5, parentheses are required around
the argument to \f(CW\*(C`given()\*(C'\fR and \f(CW\*(C`when()\*(C'\fR (except when this last one is used
as a statement modifier).  Parentheses in Perl 6 are always optional in a
control construct such as \f(CW\*(C`if()\*(C'\fR, \f(CW\*(C`while()\*(C'\fR, or \f(CW\*(C`when()\*(C'\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 Perl 6.  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 \*(L"Smartmatch Operator\*(R" in perlop is not
identical to that proposed by the Perl 6 specification, mainly due to
differences between Perl 6's and Perl 5's data models, but also because
the Perl 6 spec has changed since Perl 5 rushed into early adoption.
.PP
In Perl 6, \f(CW\*(C`when()\*(C'\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.)
