Assignment Operators

Assignment Operators

"=" is the ordinary assignment operator.

Assignment operators work as in C. That is,

$x += 2;

is equivalent to

$x = $x + 2;

although without duplicating any side effects that dereferencing the lvalue might trigger, such as from tie(). Other assignment operators work similarly. The following are recognized:

**=    +=    *=    &=    &.=    <<=    &&=
       -=    /=    |=    |.=    >>=    ||=
                  .=    %=    ^=    ^.=           //=
             x=

Although these are grouped by family, they all have the precedence of assignment. These combined assignment operators can only operate on scalars, whereas the ordinary assignment operator can assign to arrays, hashes, lists and even references. (See Context and List value constructors in perldata, and Assigning to References in perlref.)

Unlike in C, the scalar assignment operator produces a valid lvalue. Modifying an assignment is equivalent to doing the assignment and then modifying the variable that was assigned to. This is useful for modifying a copy of something, like this:

($tmp = $global) =~ tr/13579/24680/;

Although as of 5.14, that can be also be accomplished this way:

use v5.14;
$tmp = ($global =~  tr/13579/24680/r);

Likewise,

($x += 2) *= 3;

is equivalent to

$x += 2;
$x *= 3;

Similarly, a list assignment in list context produces the list of lvalues assigned to, and a list assignment in scalar context returns the number of elements produced by the expression on the right hand side of the assignment.

The three dotted bitwise assignment operators (&.= |.= ^.= ) are new in Perl 5.22 and experimental. See Bitwise String Operators.

doc_perl
2016-12-06 03:18:09
Comments
Leave a Comment

Please login to continue.