Operator Precedence and Associativity

Operator precedence determines which operators in a complex expression are evaluated first. Associativity determines how operators that have the same precedence are evaluated (where your choices are left-to-right, right-to-left, or nonassociative for those operators where order of evaluation is either not important, not guaranteed, or not even possible). Table 3.2 shows the precedence and associativity of the various operators available in Perl, with operators of a higher precedence (evaluated first) higher up in the table than those of a lower precedence (evaluated later). You'll want to fold down the corner of this page or mark it with a sticky note; this is one of those tables you'll probably refer to over and over again as you work with Perl.

You can always change the evaluation of an expression (or just make it easier to read) by enclosing it with parentheses. Expressions inside parentheses are evaluated before those outside parentheses.

Note that there are a number of operators in this table you haven't learned about yet (and some I won't cover in this book at all). I've included lesson references for those operators I do explain later on in this book.

Table 3.2. Operator Precedence and Associativity
Operator Associativity What it means
-> left Dereference operator (Day 19, “Working with References”
++ -- non Increment and decrement
** right Exponent
! ~ + - right Logical not, bitwise not, reference (Day 19), unary +, unary -
=~ !~ left Pattern matching
* / % x left Multiplication, division, modulus, string repeat
+ - . left Add, subtract, string concatenate
<< >> left Bitwise left shift and right shift
unary operators non Function-like operators (See today's “Going Deeper” section)
< > <= >= lt gt le ge non Tests
== != <=> eq ne cmp non More tests (<=> and cmp, Day 8, “Data Manipulation with Lists”)
& left Bitwise AND
| ^ left Bitwise OR, bitwise XOR
&& left C-style logical AND
|| left C-style logical OR
.. non Range operator (Day 4, “Working with Lists and Arrays”)
?: right Conditional operator (Day 6, “Conditionals and Loops”)
= += -= *= /=, etc. right Assignment operators
, => left Comma operators (Day 4)
list operators non list operators in list context (Day 4)
not right Perl logical NOT
and left Perl logical AND
or xor left Perl logical OR and XOR

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset