perlop - Perl operators and precedence
Operator precedence and associativity work in Perl more or less like
they do in mathematics.
Operator precedence means some operators are evaluated before
others. For example, in 2 + 4 * 5, the multiplication has higher
precedence so 4 * 5 is evaluated first yielding 2 + 20 ==
22 and not 6 * 5 == 30.
Operator associativity defines what happens if a sequence of the
same operators is used one after another: whether the evaluator will
evaluate the left operations first or the right. For example, in 8
- 4 - 2, subtraction is left associative so Perl evaluates the
expression left to right. 8 - 4 is evaluated first making the
expression 4 - 2 == 2 and not 8 - 2 == 6.
Perl operators have the following associativity and precedence,
listed from highest precedence to lowest. Operators borrowed from
C keep the same precedence relationship with each other, even where
C's precedence is slightly screwy. (This makes learning Perl easier
for C folks.) With very few exceptions, these all operate on scalar
values only, not array values.
left terms and list operators (leftward)
left ->
nonassoc ++ --
right **
right ! ~ \ and unary + and -
left =~ !~
left * / % x
left + - .
left << >>
nonassoc named unary operators
nonassoc < > <= >= lt gt le ge
nonassoc == != <=> eq ne cmp
left &
left | ^
left &&
left ||
nonassoc .. ...
right ?:
right = += -= *= etc.
left , =>
nonassoc list operators (rightward)
right not
left and
left or xor
In the following sections, these operators are covered in precedence order.
Many operators can be overloaded for objects. See the overload manpage.
A TERM has the highest precedence in Perl. They include variables,
quote and quote-like operators, any expression in parentheses,
and any function whose arguments are parenthesized. Actually, there
aren't really functions in this sense, just list operators and unary
operators behaving as functions because you put parentheses around
the arguments. These are all documented in the perlfunc manpage.
If any list operator (print(), etc.) or any unary operator (chdir(), etc.)
is followed by a left parenthesis as the next token, the operator and
arguments within parentheses are taken to be of highest precedence,
just like a normal function call.
In the absence of parentheses, the precedence of list operators such as
print, sort, or chmod is either very high or very low depending on
whether you are looking at the left side or the right side of the operator.
For example, in
@ary = (1, 3, sort 4, 2);
print @ary;
the commas on the right of the sort are evaluated before the sort,
but the commas on the left are evaluated after. In other words,
list operators tend to gobble up all arguments that follow, and
then act like a simple TERM with regard to the preceding expression.
Be careful with parentheses:
print($foo, exit);
print $foo, exit;
(print $foo), exit;
print($foo), exit;
print ($foo), exit;
Also note that
print ($foo & 255) + 1, "\n";
probably doesn't do what you expect at first glance. The parentheses
enclose the argument list for print which is evaluated (printing
the result of $foo & 255). Then one is added to the return value
of print (usually 1). The result is something like this:
1 + 1, "\n";
To do what you meant properly, you must write:
print(($foo & 255) + 1, "\n");
See Named Unary Operators for more discussion of this.
Also parsed as terms are the do {} and eval {} constructs, as
well as subroutine and method calls, and the anonymous
constructors [] and {}.
See also Quote and Quote-like Operators toward the end of this section,
as well as I/O Operators.
"->" is an infix dereference operator, just as it is in C
and C++. If the right side is either a [...], {...}, or a
(...) subscript, then the left side must be either a hard or
symbolic reference to an array, a hash, or a subroutine respectively.
(Or technically speaking, a location capable of holding a hard
reference, if it's an array or hash reference being used for
assignment.) See the perlreftut manpage and the perlref manpage.
Otherwise, the right side is a method name or a simple scalar
variable containing either the method name or a subroutine reference,
and the left side must be either an object (a blessed reference)
or a class name (that is, a package name). See the perlobj manpage.
"++" and "--" work as in C. That is, if placed before a variable,
they increment or decrement the variable by one before returning the
value, and if placed after, increment or decrement after returning the
value.
$i = 0; $j = 0;
print $i++;
print ++$j;
Note that just as in C, Perl doesn't define when the variable is
incremented or decremented. You just know it will be done sometime
before or after the value is returned. This also means that modifying
a variable twice in the same statement will lead to undefined behaviour.
Avoid statements like:
$i = $i ++;
print ++ $i + $i ++;
Perl will not guarantee what the result of the above statements is.
The auto-increment operator has a little extra builtin magic to it. If
you increment a variable that is numeric, or that has ever been used in
a numeric context, you get a normal increment. If, however, the
variable has been used in only string contexts since it was set, and
has a value that is not the empty string and matches the pattern
/^[a-zA-Z]*[0-9]*\z/, the increment is done as a string, preserving each
character within its range, with carry:
print ++($foo = '99');
print ++($foo = 'a0');
print ++($foo = 'Az');
print ++($foo = 'zz');
undef is always treated as numeric, and in particular is changed
to 0 before incrementing (so that a post-increment of an undef value
will return 0 rather than undef).
The auto-decrement operator is not magical.
Binary "**" is the exponentiation operator. It binds even more
tightly than unary minus, so -2**4 is -(2**4), not (-2)**4. (This is
implemented using C's pow(3) function, which actually works on doubles
internally.)
Unary "!" performs logical negation, i.e., "not". See also not for a lower
precedence version of this.
Unary "-" performs arithmetic negation if the operand is numeric. If
the operand is an identifier, a string consisting of a minus sign
concatenated with the identifier is returned. Otherwise, if the string
starts with a plus or minus, a string starting with the opposite sign
is returned. One effect of these rules is that -bareword is equivalent
to the string "-bareword". If, however, the string begins with a
non-alphabetic character (excluding "+" or "-"), Perl will attempt to convert
the string to a numeric and the arithmetic negation is performed. If the
string cannot be cleanly converted to a numeric, Perl will give the warning
Argument "the string" isn't numeric in negation (-) at ....
Unary "~" performs bitwise negation, i.e., 1's complement. For
example, 0666 & ~027 is 0640. (See also Integer Arithmetic and
Bitwise String Operators.) Note that the width of the result is
platform-dependent: ~0 is 32 bits wide on a 32-bit platform, but 64
bits wide on a 64-bit platform, so if you are expecting a certain bit
width, remember to use the & operator to mask off the excess bits.
Unary "+" has no effect whatsoever, even on strings. It is useful
syntactically for separating a function name from a parenthesized expression
that would otherwise be interpreted as the complete list of function
arguments. (See examples above under Terms and List Operators (Leftward).)
Unary "\" creates a reference to whatever follows it. See the perlreftut manpage
and the perlref manpage. Do not confuse this behavior with the behavior of
backslash within a string, although both forms do convey the notion
of protecting the next thing from interpolation.
Binary "=~" binds a scalar expression to a pattern match. Certain operations
search or modify the string $_ by default. This operator makes that kind
of operation work on some other string. The right argument is a search
pattern, substitution, or transliteration. The left argument is what is
supposed to be searched, substituted, or transliterated instead of the default
$_. When used in scalar context, the return value generally indicates the
success of the operation. Behavior in list context depends on the particular
operator. See Regexp Quote-Like Operators for details and
the perlretut manpage for examples using these operators.
If the right argument is an expression rather than a search pattern,
substitution, or transliteration, it is interpreted as a search pattern at run
time. Note that this means that its contents will be interpolated twice, so
'\\' =~ q'\\';
is not ok, as the regex engine will end up trying to compile the
pattern \, which it will consider a syntax error.
Binary "!~" is just like "=~" except the return value is negated in
the logical sense.
Binary "*" multiplies two numbers.
Binary "/" divides two numbers.
Binary "%" is the modulo operator, which computes the division
remainder of its first argument with respect to its second argument.
Given integer
operands $a and $b: If $b is positive, then $a % $b is
$a minus the largest multiple of $b less than or equal to
$a. If $b is negative, then $a % $b is $a minus the
smallest multiple of $b that is not less than $a (i.e. the
result will be less than or equal to zero). If the operands
$a and $b are floating point values and the absolute value of
$b (that is abs($b)) is less than (UV_MAX + 1), only
the integer portion of $a and $b will be used in the operation
(Note: here UV_MAX means the maximum of the unsigned integer type).
If the absolute value of the right operand (abs($b)) is greater than
or equal to (UV_MAX + 1), "%" computes the floating-point remainder
$r in the equation ($r = $a - $i*$b) where $i is a certain
integer that makes $r have the same sign as the right operand
$b (not as the left operand $a like C function fmod())
and the absolute value less than that of $b.
Note that when use integer is in scope, "%" gives you direct access
to the modulo operator as implemented by your C compiler. This
operator is not as well defined for negative operands, but it will
execute faster.
Binary "x" is the repetition operator. In scalar context or if the left
operand is not enclosed in parentheses, it returns a string consisting
of the left operand repeated the number of times specified by the right
operand. In list context, if the left operand is enclosed in
parentheses or is a list formed by qw/STRING/, it repeats the list.
If the right operand is zero or negative, it returns an empty string
or an empty list, depending on the context.
print '-' x 80;
print "\t" x ($tab/8), ' ' x ($tab%8);
@ones = (1) x 80;
@ones = (5) x @ones;
Binary "+" returns the sum of two numbers.
Binary "-" returns the difference of two numbers.
Binary "." concatenates two strings.
Binary "<<" returns the value of its left argument shifted left by the
number of bits specified by the right argument. Arguments should be
integers. (See also Integer Arithmetic.)
Binary ">>" returns the value of its left argument shifted right by
the number of bits specified by the right argument. Arguments should
be integers. (See also Integer Arithmetic.)
Note that both "<<" and ">>" in Perl are implemented directly using
"<<" and ">>" in C. If use integer (see Integer Arithmetic) is
in force then signed C integers are used, else unsigned C integers are
used. Either way, the implementation isn't going to generate results
larger than the size of the integer type Perl was built with (32 bits
or 64 bits).
The result of overflowing the range of the integers is undefined
because it is undefined also in C. In other words, using 32-bit
integers, 1 << 32 is undefined. Shifting by a negative number
of bits is also undefined.
The various named unary operators are treated as functions with one
argument, with optional parentheses.
If any list operator (print(), etc.) or any unary operator (chdir(), etc.)
is followed by a left parenthesis as the next token, the operator and
arguments within parentheses are taken to be of highest precedence,
just like a normal function call. For example,
because named unary operators are higher precedence than ||:
chdir $foo || die;
chdir($foo) || die;
chdir ($foo) || die;
chdir +($foo) || die;
but, because * is higher precedence than named operators:
chdir $foo * 20;
chdir($foo) * 20;
chdir ($foo) * 20;
chdir +($foo) * 20;
rand 10 * 20;
rand(10) * 20;
rand (10) * 20;
rand +(10) * 20;
Regarding precedence, the filetest operators, like -f, -M, etc. are
treated like named unary operators, but they don't follow this functional
parenthesis rule. That means, for example, that -f($file).".bak" is
equivalent to -f "$file.bak".
See also Terms and List Operators (Leftward).
Binary "<" returns true if the left argument is numerically less than
the right argument.
>
Binary ">" returns true if the left argument is numerically greater
than the right argument.
>>
Binary "<=" returns true if the left argument is numerically less than
or equal to the right argument.
>
Binary ">=" returns true if the left argument is numerically greater
than or equal to the right argument.
= >>
Binary "lt" returns true if the left argument is stringwise less than
the right argument.
>
Binary "gt" returns true if the left argument is stringwise greater
than the right argument.
>
Binary "le" returns true if the left argument is stringwise less than
or equal to the right argument.
>
Binary "ge" returns true if the left argument is stringwise greater
than or equal to the right argument.
>
Binary "==" returns true if the left argument is numerically equal to
the right argument.
Binary "!=" returns true if the left argument is numerically not equal
to the right argument.
Binary "<=>" returns -1, 0, or 1 depending on whether the left
argument is numerically less than, equal to, or greater than the right
argument. If your platform supports NaNs (not-a-numbers) as numeric
values, using them with "<=>" returns undef. NaN is not "<", "==", ">",
"<=" or ">=" anything (even NaN), so those 5 return false. NaN != NaN
returns true, as does NaN != anything else. If your platform doesn't
support NaNs then NaN is just a string with numeric value 0.
>>
perl -le '$a = "NaN"; print "No NaN support here" if $a == $a'
perl -le '$a = "NaN"; print "NaN support here" if $a != $a'
Binary "eq" returns true if the left argument is stringwise equal to
the right argument.
Binary "ne" returns true if the left argument is stringwise not equal
to the right argument.
Binary "cmp" returns -1, 0, or 1 depending on whether the left
argument is stringwise less than, equal to, or greater than the right
argument.
"lt", "le", "ge", "gt" and "cmp" use the collation (sort) order specified
by the current locale if use locale is in effect. See the perllocale manpage.
Binary "&" returns its operands ANDed together bit by bit.
(See also Integer Arithmetic and Bitwise String Operators.)
Note that "&" has lower priority than relational operators, so for example
the brackets are essential in a test like
print "Even\n" if ($x & 1) == 0;
Binary "|" returns its operands ORed together bit by bit.
(See also Integer Arithmetic and Bitwise String Operators.)
Binary "^" returns its operands XORed together bit by bit.
(See also Integer Arithmetic and Bitwise String Operators.)
Note that "|" and "^" have lower priority than relational operators, so
for example the brackets are essential in a test like
print "false\n" if (8 | 2) != 10;
Binary "&&" performs a short-circuit logical AND operation. That is,
if the left operand is false, the right operand is not even evaluated.
Scalar or list context propagates down to the right operand if it
is evaluated.
Binary "||" performs a short-circuit logical OR operation. That is,
if the left operand is true, the right operand is not even evaluated.
Scalar or list context propagates down to the right operand if it
is evaluated.
The || and && operators return the last value evaluated
(unlike C's || and &&, which return 0 or 1). Thus, a reasonably
portable way to find out the home directory might be:
$home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
(getpwuid($<))[7] || die "You're homeless!\n";
In particular, this means that you shouldn't use this
for selecting between two aggregates for assignment:
@a = @b || @c;
@a = scalar(@b) || @c;
@a = @b ? @b : @c;
As more readable alternatives to && and || when used for
control flow, Perl provides and and or operators (see below).
The short-circuit behavior is identical. The precedence of "and" and
"or" is much lower, however, so that you can safely use them after a
list operator without the need for parentheses:
unlink "alpha", "beta", "gamma"
or gripe(), next LINE;
With the C-style operators that would have been written like this:
unlink("alpha", "beta", "gamma")
|| (gripe(), next LINE);
Using "or" for assignment is unlikely to do what you want; see below.
Binary ".." is the range operator, which is really two different
operators depending on the context. In list context, it returns a
list of values counting (up by ones) from the left value to the right
value. If the left value is greater than the right value then it
returns the empty list. The range operator is useful for writing
foreach (1..10) loops and for doing slice operations on arrays. In
the current implementation, no temporary array is created when the
range operator is used as the expression in foreach loops, but older
versions of Perl might burn a lot of memory when you write something
like this:
for (1 .. 1_000_000) {
}
The range operator also works on strings, using the magical auto-increment,
see below.
In scalar context, ".." returns a boolean value. The operator is
bistable, like a flip-flop, and emulates the line-range (comma) operator
of sed, awk, and various editors. Each ".." operator maintains its
own boolean state. It is false as long as its left operand is false.
Once the left operand is true, the range operator stays true until the
right operand is true, AFTER which the range operator becomes false
again. It doesn't become false till the next time the range operator is
evaluated. It can test the right operand and become false on the same
evaluation it became true (as in awk), but it still returns true once.
If you don't want it to test the right operand till the next
evaluation, as in sed, just use three dots ("...") instead of
two. In all other regards, "..." behaves just like ".." does.
The right operand is not evaluated while the operator is in the
"false" state, and the left operand is not evaluated while the
operator is in the "true" state. The precedence is a little lower
than || and &&. The value returned is either the empty string for
false, or a sequence number (beginning with 1) for true. The
sequence number is reset for each range encountered. The final
sequence number in a range has the string "E0" appended to it, which
doesn't affect its numeric value, but gives you something to search
for if you want to exclude the endpoint. You can exclude the
beginning point by waiting for the sequence number to be greater
than 1.
If either operand of scalar ".." is a constant expression,
that operand is considered true if it is equal (==) to the current
input line number (the $. variable).
To be pedantic, the comparison is actually int(EXPR) == int(EXPR),
but that is only an issue if you use a floating point expression; when
implicitly using $. as described in the previous paragraph, the
comparison is int(EXPR) == int($.) which is only an issue when $.
is set to a floating point value and you are not reading from a file.
Furthermore, "span" .. "spat" or 2.18 .. 3.14 will not do what
you want in scalar context because each of the operands are evaluated
using their integer representation.
Examples:
As a scalar operator:
if (101 .. 200) { print; }
next LINE if (1 .. /^$/);
s/^/> / if (/^$/ .. eof());
while (<>) {
$in_header = 1 .. /^$/;
$in_body = /^$/ .. eof;
if ($in_header) {
} else {
}
} continue {
close ARGV if eof;
}
Here's a simple example to illustrate the difference between
the two range operators:
@lines = (" - Foo",
"01 - Bar",
"1 - Baz",
" - Quux");
foreach (@lines) {
if (/0/ .. /1/) {
print "$_\n";
}
}
This program will print only the line containing "Bar". If
the range operator is changed to ..., it will also print the
"Baz" line.
And now some examples as a list operator:
for (101 .. 200) { print; }
@foo = @foo[0 .. $#foo];
@foo = @foo[$#foo-4 .. $#foo];
The range operator (in list context) makes use of the magical
auto-increment algorithm if the operands are strings. You
can say
@alphabet = ('A' .. 'Z');
to get all normal letters of the English alphabet, or
$hexdigit = (0 .. 9, 'a' .. 'f')[$num & 15];
to get a hexadecimal digit, or
@z2 = ('01' .. '31'); print $z2[$mday];
to get dates with leading zeros.
If the final value specified is not in the sequence that the magical
increment would produce, the sequence goes until the next value would
be longer than the final value specified.
If the initial value specified isn't part of a magical increment
sequence (that is, a non-empty string matching "/^[a-zA-Z]*[0-9]*\z/"),
only the initial value will be returned. So the following will only
return an alpha:
use charnames 'greek';
my @greek_small = ("\N{alpha}" .. "\N{omega}");
To get lower-case greek letters, use this instead:
my @greek_small = map { chr } ( ord("\N{alpha}") .. ord("\N{omega}") );
Because each operand is evaluated in integer form, 2.18 .. 3.14 will
return two elements in list context.
@list = (2.18 .. 3.14);
Ternary "?:" is the conditional operator, just as in C. It works much
like an if-then-else. If the argument before the ? is true, the
argument before the : is returned, otherwise the argument after the :
is returned. For example:
printf "I have %d dog%s.\n", $n,
($n == 1) ? '' : "s";
Scalar or list context propagates downward into the 2nd
or 3rd argument, whichever is selected.
$a = $ok ? $b : $c;
@a = $ok ? @b : @c;
$a = $ok ? @b : @c;
The operator may be assigned to if both the 2nd and 3rd arguments are
legal lvalues (meaning that you can assign to them):
($a_or_b ? $a : $b) = $c;
Because this operator produces an assignable result, using assignments
without parentheses will get you in trouble. For example, this:
$a % 2 ? $a += 10 : $a += 2
Really means this:
(($a % 2) ? ($a += 10) : $a) += 2
Rather than this:
($a % 2) ? ($a += 10) : ($a += 2)
That should probably be written more simply as:
$a += ($a % 2) ? 10 : 2;
"=" is the ordinary assignment operator.
Assignment operators work as in C. That is,
$a += 2;
is equivalent to
$a = $a + 2;
although without duplicating any side effects that dereferencing the lvalue
might trigger, such as from tie(). Other assignment operators work similarly.
The following are recognized:
**= += *= &= <<= &&=
-= /= |= >>= ||=
.= %= ^=
x=
Although these are grouped by family, they all have the precedence
of assignment.
Unlike in C, the scalar assignment operator produces a valid lvalue.
Modifying an assignment is equivalent to doing the assignment and
then modifying the variable that was assigned to. This is useful
for modifying a copy of something, like this:
($tmp = $global) =~ tr [A-Z] [a-z];
Likewise,
($a += 2) *= 3;
is equivalent to
$a += 2;
$a *= 3;
Similarly, a list assignment in list context produces the list of
lvalues assigned to, and a list assignment in scalar context returns
the number of elements produced by the expression on the right hand
side of the assignment.
Binary "," is the comma operator. In scalar context it evaluates
its left argument, throws that value away, then evaluates its right
argument and returns that value. This is just like C's comma operator.
In list context, it's just the list argument separator, and inserts
both its arguments into the list. These arguments are also evaluated
from left to right.
The => operator is a synonym for the comma, but forces any word
(consisting entirely of word characters) to its left to be interpreted
as a string (as of 5.001). This includes words that might otherwise be
considered a constant or function call.
use constant FOO => "something";
my %h = ( FOO => 23 );
is equivalent to:
my %h = ("FOO", 23);
It is NOT:
my %h = ("something", 23);
If the argument on the left is not a word, it is first interpreted as
an expression, and then the string value of that is used.
The => operator is helpful in documenting the correspondence
between keys and values in hashes, and other paired elements in lists.
%hash = ( $key => $value );
login( $username => $password );
On the right side of a list operator, it has very low precedence,
such that it controls all comma-separated expressions found there.
The only operators with lower precedence are the logical operators
"and", "or", and "not", which may be used to evaluate calls to list
operators without the need for extra parentheses:
open HANDLE, "filename"
or die "Can't open: $!\n";
See also discussion of list operators in Terms and List Operators (Leftward).
Unary "not" returns the logical negation of the expression to its right.
It's the equivalent of "!" except for the very low precedence.
Binary "and" returns the logical conjunction of the two surrounding
expressions. It's equivalent to && except for the very low
precedence. This means that it short-circuits: i.e., the right
expression is evaluated only if the left expression is true.
Binary "or" returns the logical disjunction of the two surrounding
expressions. It's equivalent to || except for the very low precedence.
This makes it useful for control flow
print FH $data or die "Can't write to FH: $!";
This means that it short-circuits: i.e., the right expression is evaluated
only if the left expression is false. Due to its precedence, you should
probably avoid using this for assignment, only for control flow.
$a = $b or $c;
($a = $b) or $c;
$a = $b || $c;
However, when it's a list-context assignment and you're trying to use
"||" for control flow, you probably need "or" so that the assignment
takes higher precedence.
@info = stat($file) || die;
@info = stat($file) or die;
Then again, you could always use parentheses.
Binary "xor" returns the exclusive-OR of the two surrounding expressions.
It cannot short circuit, of course.
Here is what C has that Perl doesn't:
- unary &
-
Address-of operator. (But see the "\" operator for taking a reference.)
- unary *
-
Dereference-address operator. (Perl's prefix dereferencing
operators are typed: $, @, %, and &.)
- (TYPE)
-
Type-casting operator.
While we usually think of quotes as literal values, in Perl they
function as operators, providing various kinds of interpolating and
pattern matching capabilities. Perl provides customary quote characters
for these behaviors, but also provides a way for you to choose your
quote character for any of them. In the following table, a {} represents
any pair of delimiters you choose.
Customary Generic Meaning Interpolates
'' q{} Literal |