[Israel.pm] 2 Qs on assignment and evaluation
mellerf at netvision.net.il
Thu Jan 29 11:47:01 PST 2004
-----BEGIN PGP SIGNED MESSAGE-----
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,
|> However, my $a=1 ; my $b; print "\n", $b=$a+1, $a=3, "\n"; prints
|> 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:
outputs 2 (@a in scalar context), while
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
$b=@a; # assignment returna assigned variable
I hope I made myself clear and that this makes sense. if not, feel free
to correct me, of course.
My public key:
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org
-----END PGP SIGNATURE-----
More information about the Perl