Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Will "$_[0]=shift" always resolve shift first?

by betterworld (Curate)
on Sep 08, 2008 at 21:44 UTC ( [id://709888]=note: print w/replies, xml ) Need Help??


in reply to Will "$_[0]=shift" always resolve shift first?

As you can see from the listing in perlop, the assignment operator ("=") has right associativity, which means that the right side is evaluated before the left side.

Incidentally, this is the very reason that the following common idiom works as you expect:

$x = $y = 42;

Had "=" its left side evaluated first, the 42 would not make it into the $y variable, which would lead to code breakage all over the planet ;)

Update: Hm, scratch that, I think I confused a few terms. The associativity tells us how the statement gets parsed, not how it gets executed.

Replies are listed 'Best First'.
Re^2: Will "$_[0]=shift" always resolve shift first?
by ikegami (Patriarch) on Sep 08, 2008 at 22:00 UTC

    Associativity controls the order in which operators are evaluated in a chain of operators of the same precedence.

    If operand evaluation order was tied to operator precedence and associativity, bar() would be evaluated before foo() in

    foo() + bar() * baz()

    (It's not.)

Re^2: Will "$_[0]=shift" always resolve shift first?
by GrandFather (Saint) on Sep 08, 2008 at 23:55 UTC

    So what would you expect the following to print?

    use strict; my @array = (0, 0, 0); my $x = 0; $array[++$x] = $x++; print "@array\n"; $x = 0; $array[++$x] = $x; print "@array\n"; $x = 0; $array[++$x] = ++$x; print "@array\n";

    Perl reduces RSI - it saves typing

      What is your point?

      If your point was to contradict betterworld, it doesn't. While it may not *appear* to be the case, the RHS of the assignment is evaluated before the LHS in every instance.

      If your point is that it can get very complex very fast, I agree.

        In the last case ($array[++$x] = ++$x;) both $x pre-increments are evaluated before the content of $x is returned as the value for the RHS (2 is assigned) so at least part of the LHS calculation is performed before the RHS is fully evaluated.


        Perl reduces RSI - it saves typing

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2024-04-25 17:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found