ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> activeperl
activeperl
Re: Why does this work?
by Casteele/ShadowLord other posts by this author
May 22 2008 2:15AM messages near this date
Why does this work? | Re: Why does this work?
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 p
rimary 
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
ActivePerl@[...].com
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs
Thread:
Barry Brevik
Casteele/ShadowLord
Jenda Krynicky

Privacy Policy | Email Opt-out | Feedback | Syndication
© ActiveState Software Inc. All rights reserved