perlsyn - Perl syntax: declarations, statements, comments
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.
Perl is a free-form 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.
Many of Perl's syntactic elements are optional. 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 Do What I Mean, abbreviated DWIM. It allows programmers to be lazy and to code in a style with which they are comfortable.
Perl borrows syntax 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.
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 (undef
) until it has been assigned a defined value, which is anything other than undef
. When used as a number, undef
is treated as 0
; when used as a string, it is treated as the empty string, ""
; 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 undef
as a string or a number. Well, usually. Boolean contexts, such as:
if ($x) {}
are exempt from warnings (because they care about truth rather than definedness). Operators such as ++
, --
, +=
, -=
, and .=
, that operate on undefined variables such as:
undef $x;
$x++;
are also always exempt from such warnings.
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 my()
, state()
, or our()
, 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.
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 sub name
, thus:
sub myname;
$me = myname $0 or die "can't get myname";
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 or
instead of ||
.) The ||
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 ($)
to turn the subroutine into a unary operator:
sub myname ($);
$me = myname $0 || die "can't get myname";
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.
Subroutines declarations can also be loaded up with the require
statement or both loaded and imported into your namespace with a use
statement. See perlmod for details on this.
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.
Text from a "#"
character until the end of the line is a comment, and is ignored. Exceptions include "#"
inside a string or regular expression.
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 eval {}
, sub {}
, and do {}
that look 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.
Any simple statement may optionally be followed by a SINGLE modifier, just before the terminating semicolon (or block ending). The possible modifiers are:
if EXPR
unless EXPR
while EXPR
until EXPR
for LIST
foreach LIST
when EXPR
The EXPR
following the modifier is referred to as the "condition". Its truth or falsehood determines how the modifier will behave.
if
executes the statement once if and only if the condition is true. unless
is the opposite, it executes the statement unless the condition is true (that is, if the condition is false). See "Scalar values" in perldata for definitions of true and false.
print "Basset hounds got long ears" if length $ear >= 10;
go_outside() and play() unless $is_raining;
The for(each)
modifier is an iterator: it executes the statement once for each item in the LIST (with $_
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.
print "Hello $_!\n" for qw(world Dolly nurse);
while
repeats the statement while the condition is true. Postfix while
has the same magic treatment of some kinds of condition that prefix while
has. until
does the opposite, it repeats the statement until the condition is true (or while the condition is false):
# Both of these count from 0 to 10.
print $i++ while $i <= 10;
print $j++ until $j > 10;
The while
and until
modifiers have the usual "while
loop" semantics (conditional evaluated first), except when applied to a do
-BLOCK (or to the Perl4 do
-SUBROUTINE statement), in which case the block executes once before the conditional is evaluated.
This is so that you can write loops like:
do {
$line = <STDIN>;
...
} until !defined($line) || $line eq ".\n"
See "do" in perlfunc. Note also that the loop control statements described later will NOT work in this construct, because modifiers don't take loop labels. Sorry. You can always put another block inside of it (for next
/redo
) or around it (for last
) to do that sort of thing.
For next
or redo
, just double the braces:
do {{
next if $x == $y;
# do something here
}} until $x++ > $z;
For last
, you have to be more elaborate and put braces around it:
{
do {
last if $x == $y**2;
# do something here
} while $x++ <= $z;
}
If you need both next
and last
, you have to do both and also use a loop label:
LOOP: {
do {{
next if $x == $y;
last LOOP if $x == $y**2;
# do something here
}} until $x++ > $z;
}
NOTE: The behaviour of a my
, state
, or our
modified with a statement modifier conditional or loop construct (for example, my $x if ...
) is undefined. The value of the my
variable may be undef
, 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.
The when
modifier is an experimental feature that first appeared in Perl 5.14. To use it, you should include a use v5.14
declaration. (Technically, it requires only the switch
feature, but that aspect of it was not available before 5.14.) Operative only from within a foreach
loop or a given
block, it executes the statement only if the smartmatch $_ ~~ EXPR
is true. If the statement executes, it is followed by a next
from inside a foreach
and break
from inside a given
.
Under the current implementation, the foreach
loop can be anywhere within the when
modifier's dynamic scope, but must be within the given
block's lexical scope. This restriction may be relaxed in a future release. See "Switch Statements" below.
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).
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 ;
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 +
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.
The following compound statements may be used to control flow:
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
As of Perl 5.36, you can iterate over multiple values at a time by specifying a list of lexicals within parentheses:
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
If enabled by the experimental try
feature, the following may also be used
try BLOCK catch (VAR) BLOCK
try BLOCK catch (VAR) BLOCK finally BLOCK
The experimental given
statement is not automatically enabled; see "Switch Statements" below for how to do so, and the attendant caveats.
Unlike in C and Pascal, in Perl these are all defined in terms of BLOCKs, not statements. This means that the curly brackets are required--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:
if (!open(FOO)) { die "Can't open $FOO: $!" }
die "Can't open $FOO: $!" unless open(FOO);
open(FOO) || die "Can't open $FOO: $!";
open(FOO) ? () : die "Can't open $FOO: $!";
# a bit exotic, that last one
The if
statement is straightforward. Because BLOCKs are always bounded by curly brackets, there is never any ambiguity about which if
an else
goes with. If you use unless
in place of if
, the sense of the test is reversed. Like if
, unless
can be followed by else
. unless
can even be followed by one or more elsif
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.
The while
statement executes the block as long as the expression is true. The until
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 next
, last
, and redo
. 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 use warnings
pragma or the -w flag.
If the condition expression of a while
statement is based on any of a group of iterative expression types then it gets some magic treatment. The affected iterative expression types are readline
, the <FILEHANDLE>
input operator,