Assignment Operators
Perl recognizes the C assignment operators, as well as providing some of its own. There are quite a few of them:
= **= += *= &= <<= &&= -= /= |= >>= ||= .= %= ^= x=
Each operator requires a target lvalue (typically a variable or array element) on the left side and an expression on the right side. For the simple assignment operator:
TARGET
=EXPR
the value of the EXPR
is stored into
the variable or location designated by
TARGET
. For the other operators, Perl
evaluates the expression:
TARGET
OP
=EXPR
as if it were written:
TARGET
=TARGET
OP
EXPR
That's a handy mental rule, but it's misleading in two ways.
First, assignment operators always parse at the precedence level of
ordinary assignment, regardless of the precedence that
OP
would have by itself. Second,
TARGET
is evaluated only once. Usually that
doesn't matter unless there are side effects, such as an
autoincrement:
$var[$a++] += $value; # $a is incremented once $var[$a++] = $var[$a++] + $value; # $a is incremented twice
Unlike in C, the assignment operator produces a valid lvalue. Modifying an assignment is equivalent to doing the assignment and then modifying the variable to which it was assigned. This is useful for modifying a copy of something, like this:
($tmp = $global) += $constant;
which is the equivalent of:
$tmp = $global + $constant;
Likewise:
($a += 2) *= 3;
is equivalent to:
$a += 2; $a *= 3;
That's not terribly useful, but here's an idiom you see frequently:
($new = $old) =~ s/foo/bar/g;
In all ...
Get Programming Perl, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.