Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Re: Mysterious for behavior

by Roy Johnson (Monsignor)
on Apr 21, 2004 at 19:32 UTC ( #347106=note: print w/replies, xml ) Need Help??


in reply to Re: Mysterious for behavior
in thread Mysterious for behavior

Actually (and this was the point of confusion), I made $_ an alias to $i three times. I would have understood if it had acted like
for (scalar($i=3, $i=2, $i=1)) { print "$_ and $i\n"; }
where each assignment happens in turn, because of the comma operator, and $_ is aliased to the final result ($i) once. But that didn't happen. I expected each assignment expression to yield the value of its right-hand side, but Perl evaluated it more like:
$i=3, $i=2, $i=1; for ($i, $i, $i) { print "$_ and $i\n"; }

The interesting part

I can get the effect I expected by doing this:
for (0+($i=3), 0+($i=2), $i=1) { print "$_ and $i\n"; }

The PerlMonk tr/// Advocate

Replies are listed 'Best First'.
Re: Re: Re: Mysterious for behavior
by borisz (Canon) on Apr 21, 2004 at 19:46 UTC
    I can get the effect I expected by doing this:
    for (0+($i=3), 0+($i=2), $i=1) { print "$_ and $i\n"; }
    In your example you create
    for ( temp, temp2, $i ) {
    Boris
Re: Re: Re: Mysterious for behavior
by Belgarion (Chaplain) on Apr 21, 2004 at 20:00 UTC

    Maybe a better way to think about it is that you created an array of three elements, each element is pointing to the $i variable. However, because you are initializing $i for each element in the list, the elements in the list all contain the same value (in this case, the final value of $i: 1), since they're pointing to the current value of $i.

Re: Re: Re: Mysterious for behavior
by ysth (Canon) on Apr 21, 2004 at 22:18 UTC
    Scalar assignments yield the lvalue on the left, not the value on the right. Now can you make that fit with your "interesting part" and understand why it works as it does?
      I didn't have any difficulty understanding why the interesting part worked.

      The PerlMonk tr/// Advocate

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://347106]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2022-05-28 01:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (98 votes). Check out past polls.

    Notices?