Skip to Content
Programming Perl, 3rd Edition
book

Programming Perl, 3rd Edition

by Larry Wall, Tom Christiansen, Jon Orwant
July 2000
Intermediate to advanced
1104 pages
35h 1m
English
O'Reilly Media, Inc.
Content preview from Programming Perl, 3rd Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Perl, 4th Edition

Programming Perl, 4th Edition

Tom Christiansen, brian d foy, Larry Wall, Jon Orwant
Learning Perl, 7th Edition

Learning Perl, 7th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Programming the Perl DBI

Programming the Perl DBI

Tim Bunce, Alligator Descartes

Publisher Resources

ISBN: 0596000278Supplemental ContentErrata