=head1 NAME
X
perlop - Perl operators and precedence
=head1 DESCRIPTION
In Perl, the operator determines what operation is performed,
independent of the type of the operands. For example S>
is always a numeric addition, and if C or C do not contain
numbers, an attempt is made to convert them to numbers first.
This is in contrast to many other dynamic languages, where the
operation is determined by the type of the first argument. It also
means that Perl has two versions of some operators, one for numeric
and one for string comparison. For example S> compares
two numbers for equality, and S> compares two strings.
There are a few exceptions though: C can be either string
repetition or list repetition, depending on the type of the left
operand, and C, C, C and C can be either string or numeric bit
operations.
=head2 Operator Precedence and Associativity
X X X
Operator precedence and associativity work in Perl more or less like
they do in mathematics.
I means some operators group more tightly than others.
For example, in C, the multiplication has higher precedence, so C is grouped together as the right-hand operand of the addition, rather
than C being grouped together as the left-hand operand of the
multiplication. It is as if the expression were written C, not
C. So the expression yields C, rather than
C.
I defines what happens if a sequence of the same
operators is used one after another:
usually that they will be grouped at the left
or the right. For example, in C, subtraction is left associative,
so C is grouped together as the left-hand operand of the second
subtraction, rather than C being grouped together as the right-hand
operand of the first subtraction. It is as if the expression were written
C, not C. So the expression yields C,
rather than C.
For simple operators that evaluate all their operands and then combine the
values in some way, precedence and associativity (and parentheses) imply some
ordering requirements on those combining operations. For example, in C, the grouping implied by precedence means that the multiplication of 4 and
5 must be performed before the addition of 2 and 20, simply because the result
of that multiplication is required as one of the operands of the addition. But
the order of operations is not fully determined by this: in C
both multiplications must be performed before the addition, but the grouping
does not say anything about the order in which the two multiplications are
performed. In fact Perl has a general rule that the operands of an operator
are evaluated in left-to-right order. A few operators such as C have
special evaluation rules that can result in an operand not being evaluated at
all; in general, the top-level operator in an expression has control of
operand evaluation.
Some comparison operators, as their associativity, I with some
operators of the same precedence (but never with operators of different
precedence). This chaining means that each comparison is performed
on the two arguments surrounding it, with each interior argument taking
part in two comparisons, and the comparison results are implicitly ANDed.
Thus S $y E= $z">> behaves exactly like S
$y && $y E= $z">>, assuming that C is as simple a scalar as
it looks. The ANDing short-circuits just like C does, stopping
the sequence of comparisons as soon as one yields false.
In a chained comparison, each argument expression is evaluated at most
once, even if it takes part in two comparisons, but the result of the
evaluation is fetched for each comparison. (It is not evaluated
at all if the short-circuiting means that it's not required for any
comparisons.) This matters if the computation of an interior argument
is expensive or non-deterministic. For example,
if($x > is an error.
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 isa
chained = lt gt le ge
chain/na == != eq ne cmp ~~
left & &.
left | |. ^ ^.
left &&
left || //
nonassoc .. ...
right ?:
right = += -= *= etc. goto last next redo dump
left , =>
nonassoc list operators (rightward)
right not
left and
left or xor
In the following sections, these operators are covered in detail, in the
same order in which they appear in the table above.
Many operators can be overloaded for objects. See L.
=head2 Terms and List Operators (Leftward)
X X X
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 L.
If any list operator (C, etc.) or any unary operator (C, 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
C, C, or C 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; # prints 1324
the commas on the right of the C are evaluated before the C,
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:
# These evaluate exit before doing the print:
print($foo, exit); # Obviously not what you want.
print $foo, exit; # Nor is this.
# These do the print before evaluating exit:
(print $foo), exit; # This is what you want.
print($foo), exit; # Or this.
print ($foo), exit; # Or even this.
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 C which is evaluated (printing
the result of S>). Then one is added to the return value
of C (usually 1). The result is something like this:
1 + 1, "\n"; # Obviously not what you meant.
To do what you meant properly, you must write:
print(($foo & 255) + 1, "\n");
See L for more discussion of this.
Also parsed as terms are the S> and S> constructs, as
well as subroutine and method calls, and the anonymous
constructors C and C.
See also L toward the end of this section,
as well as L"I/O Operators">.
=head2 The Arrow Operator
X X X >>
"C >>" is an infix dereference operator, just as it is in C
and C++. If the right side is either a C, C, or a
C 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 L and L.
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 L.
The dereferencing cases (as opposed to method-calling cases) are
somewhat extended by the C feature. For the
details of that feature, consult L.
=head2 Auto-increment and Auto-decrement
X X X X X X
C and C 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++; # prints 0
print ++$j; # prints 1
Note that just as in C, Perl doesn't define B 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 behavior.
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
C^[a-zA-Z]*[0-9]*\z/>, the increment is done as a string, preserving each
character within its range, with carry:
print ++($foo = "99"); # prints "100"
print ++($foo = "a0"); # prints "a1"
print ++($foo = "Az"); # prints "Ba"
print ++($foo = "zz"); # prints "aaa"
C is always treated as numeric, and in particular is changed
to C before incrementing (so that a post-increment of an undef value
will return C rather than C).
The auto-decrement operator is not magical.
=head2 Exponentiation
X X X
Binary C is the exponentiation operator. It binds even more
tightly than unary minus, so C is C, not C.
(This is
implemented using C's C function, which actually works on doubles
internally.)
Note that certain exponentiation expressions are ill-defined:
these include C, C, and C. Do not expect
any particular results from these special cases, the results
are platform-dependent.
=head2 Symbolic Unary Operators
X X
Unary C performs logical negation, that is, "not". See also
L|/Logical Not> for a lower precedence version of this.
X
Unary C performs arithmetic negation if the operand is numeric,
including any string that looks like a number. 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 C is equivalent
to the string C. If, however, the string begins with a
non-alphabetic character (excluding C or C), 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
B.
X X
Unary C performs bitwise negation, that is, 1's complement. For
example, S> is 0640. (See also L and
L.) Note that the width of the result is
platform-dependent: C 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 C operator to mask off the excess bits.
X X
Starting in Perl 5.28, it is a fatal error to try to complement a string
containing a character with an ordinal value above 255.
If the "bitwise" feature is enabled via S> or C