Perl recognizes the C assignment operators, as well as providing some of its own. There are quite a few of them:
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:= **= += *= &= <<= &&= -= /= |= >>= ||= .= %= ^= x=
the value of the EXPR is stored into the variable or location designated by TARGET. For the other operators, Perl evaluates the expression:TARGET = EXPR
as if it were written: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:TARGET = TARGET OP EXPR
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:$var[$a++] += $value; # $a is incremented once $var[$a++] = $var[$a++] + $value; # $a is incremented twice
which is the equivalent of:($tmp = $global) += $constant;
Likewise:$tmp = $global + $constant;
is equivalent to:($a += 2) *= 3;
That's not terribly useful, but here's an idiom you see frequently:$a += 2; $a *= 3;
In all cases, the value of the assignment is the new value of the variable. Since assignment operators associate right-to-left, this can be used to assign many variables the same value, as in:($new = $old) =~ s/foo/bar/g;
which assigns 0 to $c, and the result of that (still 0) to $b, and the result of that (still0) to $a.$a = $b = $c = 0;
List assignment may be done only with the plain assignment operator, =. In list context, list assignment returns the list of new values just as scalar assignment does. In scalar context, list assignment returns the number of values that were available on the right side of the assignment, as mentioned in Chapter 2, "Bits and Pieces". This makes it useful for testing functions that return a null list when unsuccessful (or no longer successful), as in:
while (($key, $value) = each %gloss) { ... } next unless ($dev, $ino, $mode) = stat $file;
Copyright © 2002 O'Reilly & Associates. All rights reserved.