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:
TARGETOP=EXPR
as if it were written:
TARGET=TARGETOPEXPR
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 ...