SPUG: return value of assignment operator

Michael R. Wolf MichaelRWolf at att.net
Wed Apr 30 10:50:44 PDT 2008

C's assignment operator returns "the value assigned to the LHS".

Perl's assignment operator "returns a valid lvalue".

I knew both facts independently, but just recently held them in my head at
the same time.  It got me thinking "Why should Perl be different?".  Here's
what I've come up with.

For statements like this, it wouldn't matter LHS or RHS:

    $x = $y = $z = 0;

    if (($line = <>) != "\n") {...}

But returning an lvalue allows statements like these, where a copy can be
taken and also changed in the same statement.

    ($x = $y = 0)++;

    $x = ($y = $z = 0)++;	# Do you *really* know what's in $x and

    ($incremented_copy = $original_unchanged)++;

    ($changed_copy = $original_string) =~ s/\s//;

Theoretically, I like the flexibility it gives.

Practically, I'd advocate against excessive use (for some definition of
'excess' that I'm currently wrestling with).

Open questions for discussion:
  * Where do you rely on assignment returning the LHS?  
  * What definition of "excess" prevents you from using it further?
  * Which languages return lvalues, RHS, or are unspecified?

lvalue:    Perl
RHS:       C, C++, JavaScript
Undefined: shell

Michael R. Wolf
    All mammals learn by playing!
        MichaelRWolf at att.net

More information about the spug-list mailing list