Operator Precedence and Associativity
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 first. 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. 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 precedence order.
Many operators can be overloaded for objects. See overload.
Please login to continue.