[Israel.pm] 2 Qs on assignment and evaluation

Yosef Meller mellerf at netvision.net.il
Thu Jan 29 11:47:01 PST 2004

Hash: SHA1

Offer Kaye wrote:
|> You seem to be correct.  I tried my $a=2; print "\n", $a, $a=3,
|> "\n"; and this results in 33 being printed.
|> This is very un-C like behaviour! And, in my opinion,
|> non-intitutive.
|> However, my $a=1 ; my $b; print "\n", $b=$a+1, $a=3, "\n"; prints
|> 23
|> So, this seems to be strange, because in a similar vein as Ofer
|> suggested, $b which is first set to 2 (1+1), should be reset to 4
|> (3+1). But this doesn't happen. Why?
|> Best regards, Srikanth
| I think the difference between the two examples you gave above are
| that in the first you modify the same variable, while in the second
| example you modify a different variable, so once $b in this case has
| been evaluated it will not change even when $a does. But I'm just
| guessing here.
| If you think the above examples you gave are strange, check this out:
|  my ($a,$b)=(1,1); print  $a ,$a=3,"\n";   # prints 33 print
| "$b",$b=3,"\n"; # prints 13
| Now for this I really have no explanation, except again to guess that
| once the string is evaluated, it does not change (remember that print
| goes over the list from left to right). Anyone has any idea if I'm
| right and where is this documented?
| I guess the conclusion is, don't modify and use the same variable in
| the same statement, you may not get what you think you'll get :-)
| ---------------------------------- Offer Kaye

Can I have a go too? :-)

Consider the following quote from perlop:
** "Modifying an assignment is equivalent to doing the assignment and then
** modifying the variable that was assigned to.  This is useful for modi-
** fying a copy of something ... "

So, what I say is, the return value from an assignment is not the value
assigned, but the variable being assigned to. so the return value of
"$a=2" is not 2, but $a (a sort of a reference).

When we do something like $a=$b=5 we get: $b=5, $a=$b ---> $a=5
But when we do: print $a=2, $a++ we actually get $a=2, then $a++ (now
3), and then, using the return values from both, we have "print $a, 2"
which is now the same as "print 3, 2".

To support my theory further, see that:
print $b=@a=5;
outputs 2 (@a in scalar context), while
print $b=(5,6);
outputs 6 (the last value of the list).
So the evaluation order of "print $b=@a=(5,6);" is not:
$b=(5,6); # assignment returns value
print $b;

But rather:
$b=@a; # assignment returna assigned variable
print $b;

I hope I made myself clear and that this makes sense. if not, feel free
to correct me, of course.

- --
perl -e'$b=unpack"b*",pack"H*","59dfce2d6b1664d3b26cd9969503";

My public key:
Version: GnuPG v1.2.1 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org


More information about the Perl mailing list