Bug#655063: syntax error not caught ($h+=9)=(3)

Russ Allbery rra at debian.org
Sun Jan 8 18:14:38 UTC 2012


jidanni at jidanni.org writes:

> $ perl -lwe 'use strict;my $h;($h+=9)=(3); print $h'
> 3

> If it is not a syntax error then it should be.

If Perl were a different language with different semantics, it could be a
syntax error, but it's not.  I don't see how that could be a syntax error
without changing the way Perl works in ways that wouldn't be backward
compatible.

The expression "$h += 9" adds 9 to $h and then returns $h as an lvalue
(meaning that it can be assigned to again).  This is because "$h += 9" is
entirely equivalent to "$h = $h + 9" and assignment returns an lvalue, as
documented in perlop:

       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 [0-9] [a-j];

       Likewise,

           ($a += 2) *= 3;

       is equivalent to

           $a += 2;
           $a *= 3;

The expression "($h += 9)" is therefore a list of lvalues containing one
lvalue, and you can assign a list of values to a list of lvalues in Perl.
(If you couldn't, the expression "my ($a, $b) = (1, 2)" wouldn't work,
which would break a ton of Perl code.)  Also, this expression is very
similar to the "($a += 2) *= 3" expression that's explicitly documented as
working in perlop.

So while this is confusing, this is the language working as it is
documented to work.

-- 
Russ Allbery (rra at debian.org)               <http://www.eyrie.org/~eagle/>






More information about the Perl-maintainers mailing list