On 20 May 2008 at 15:53, Barry Brevik wrote:
> OK, I've stumped myself. I wanted to assign 0 to several variables,
> except for a single variable that should be set to 1.
>
> Before I knew what I was doing I whipped this code into my editor:
>
> ($frow = $ax = $bx = $cx = 0)++;
>
> ...and it works as I expected. That is, all of the variables are set
> to 0 except $frow which is 1.
>
> Now I'm afraid that it might not always work because I don't
> understand why it works in the first case. Anyone want to suggest if
> this is stable code or not?
>
> Barry Brevik
It works (but is not a good way of doing what you want to do!) because the only
way for Perl
to properly evaluate something like "$x = $y = $z = 0" is by making assignment
a side effect
of the "=" operator, and making the "=" operator return the variable assigned.
You read that
right: Assigning a value to a variable is only a side effect of the "="
operator, not it's primary
operation. It's primary operation is to return the variable that was assigned!
(That is also why
you can do something like "somefunction($x = 4);", which is the same as "$x =
4;
somefunction($x);")
The code you wrote is the same as:
($frow = ($ax = ($bx = ($cx = 0))))++;
Breaking that down, you'll have..
After evaluating "($cx = 0)" and replacing it with "$cx"
($frow = ($ax = ($bx = $cx)))++;
After evaluating "($bx = $cx)" and replacing it with "$bx"
($frow = ($ax = $bx))++;
After evaluating "($ax = $bx)" and replacing it with "$ax"
($frow = $ax)++;
After evaluating "($frow = $ax)" and replacing it with "$frow"
$frow++;
The last I think you can figure out for yourself..
_______________________________________________
ActivePerl mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs