in reply to Re: ternary conditional help
in thread ternary conditional help

ok thanks, but how is it that  ($a = 2) = 'x' makes $a = 'x' ?

Replies are listed 'Best First'.
Re^3: ternary conditional help
by haukex (Archbishop) on Nov 28, 2016 at 20:46 UTC

    Hi opaltoot,

    See Assignment Operators:

    ... the scalar assignment operator produces a valid lvalue. Modifying an assignment is equivalent to doing the assignment and then modifying the variable that was assigned to. This is useful for modifying a copy of something, like this:

    ($tmp = $global) =~ tr/13579/24680/;

    ... Likewise,

    ($x += 2) *= 3;

    is equivalent to

    $x += 2; $x *= 3;

    Hope this helps,
    -- Hauke D

      thanks, yes that helps
Re^3: ternary conditional help
by tybalt89 (Monsignor) on Nov 28, 2016 at 20:50 UTC

      This is because the entire expression is evaluated before being passed as arguments to print. print doesn't get called iteratively for each argument. It gets its arguments, and then iterates.

      So that means $a = 2 is evaluated, then ' ', then $a = 3, and then the values of $a, ' ', and $a are passed to print. By the time the expression has been evaluated, $a contains 3 no matter how many times it appears in @_.


      Dave

        Well, I would characterize the reason as having more to do with the fact that passing $a = 2 as an argument causes an alias to $a to be put into @_. Had a copy of $a's value been placed into @_ instead, then subsequently changing $a to 3 would not impact that copy.

        print $a = 1, 0+$a, $a = 2, 0+$a, $a = 3, 0+$a; # prints "313233"

        The reason that $a = 2 passes an alias is because it is an "lvalue" expression, which just means that you can do previously mentioned things like ( $a = 2 ) = 3. And the reason that lvalue expressions cause aliases to be passed is two-fold: So you can modify arguments via code like $_[0] = 3 in your sub and because it is more efficient than creating a copy.

        - tye        

        This is because the entire expression is evaluated before being passed as arguments to print

        No, the arguments are placed on the stack as they are evaluated.

        1. $a = 2 is evaluated and the result ($a) is placed on the stack.
        2. ' ' is evaluated and the result is placed on the stack.
        3. $a = 3 is evaluated and the result ($a) is placed on the stack.
        4. "\n" is evaluated and the result is placed on the stack.
        5. print is evaluated.

        @_ isn't even constructed here since print is an operator, not a sub.

        The reason you get the observed behaviour is that $a itself (not a copy of it) is placed on the stack.