What does += mean in perl?

Dani AI

Generated

gave the straightforward explanation and fixed the typo and pointed to the docs. A few practical follow-ups and gotchas that often help later.

A very common idiom is counting with a hash key; using the addition-assignment on an absent key will create the key and treat the undef as zero. For example:

$counts{$word} += 1;

If warnings are enabled, adding a non-numeric string will emit "Argument ... isn't numeric" — to avoid that or to be explicit, initialize with the defined-or operator first:

$counts{$word} //= 0;
$counts{$word} += 1;

String concatenation uses a different assignment operator; use the concatenation-assignment when you want to append text:

$message .= " more text";

If the left-hand side is a tied variable or an object, the behaviour can be different: tied variables will have their FETCH and STORE methods invoked around the operation, and objects that overload the addition/concatenation operators will have those overloads applied. That means using += can trigger class or tie code — useful, but worth being aware of when debugging.

Further reading: Perl's operator/assignment details and related topics are documented in the Perl manual — see the Assignment Operators section in perlop and the tie/overload docs for the tied-variable and object-overload behavior:

Practical takeaways: use //= to initialize counters, prefer ++ for simple increments when clarity matters, and enable warnings while you develop so accidental string-to-number coercions show up.

Recommended Answers

All 3 Replies

$x += $y

means the same thing as

$x = $x + y

with the exception that $x is evaluated only once -- this would only make a difference if evaluating $x had side effects (e.g. when it's not really a variable but actually a subroutine call).

You can use the same op= syntax for any of Perl's operators, like *=, -=, /=, <<=, .=, etc. and the semantics are the same.

Hi Trentacle,
I suppose you really want to write:

   $x = $x + $y;

instead of

$x = $x + y

Hi tunisia,
In addition to what Trentacle wrote you could read **Assignment Operators ** under

     perldoc perlop 

documentation from your Command Line Interface.

Quite so. Thanks for catching my mistake.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.