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";
    <prints>
    0 0 0 0 1 0 0 1 2

    with Perl 5.8.7.


    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