in reply to Re: precedence question
in thread precedence question

First of all, sorry about the additional post; refreshing the page on my browser had that unfortunate side effect. However, disregarding where I put the result, suppose I changed it to :
#!/usr/bin/perl $a = 10; $result = ($a+=5) + ($a-=10); print "$result";
My question is, since the assignment is made to the scalar variable $a using += and -= at supposedly different times, which parentheses is evaluated first? Or are they evaluated at the same time? I know there are different ways to do this; this is a kind of "What is the philosophy of Perl on this situation?" type of question, because I was curious. The possible answers I can see are:
1: parenthesis right to left: (0+5)+(10-10) = 5.
2: parenthesis left to right: (10+5)+(15-10) = 20.
3: parenthesis simultaneously: (10+5)+(10-10) = 15.
However, when this is run, with the modifications above, I still get 10 as an answer.

Replies are listed 'Best First'.
Re: Re: Re: precedence question
by waswas-fng (Curate) on Aug 09, 2002 at 22:10 UTC
    Take this example:
    $a = 30; $one = ($a += 5) + ($a -= 10); print "a=$a one= $one \n";
    Output: a=25 one=50 it looks the the += is being updated after the calculation: so (30) + (30 - 10) = 50 then after the line passes you see $a is 25. Not sure if this is how it should work or not seems kinda fishy that the += is not proccessed the same way -= is. but i still don't understand what you are trying to add up here? $result = ($a+=5) + ($a-=10); is not very intuitive. Do you expect $result to be the result status of the += or -=? I am not sure what I would even expect $result to hold += and -= are not really normal arithmatic operators...

    -Waswas
      The way it was explained to me, the value of $a is modified with all the parenthetical calls, and then the result is added. So the actual calculation would end up being:
      $a = 30
      then $a = 35 (after the +=5)
      then $a = 25 (after the -=10)
      then $one = $a + $a, or (25)+(25) = 50, our answer.
      I knew the code wasn't intuitive; it was presented as a specifically nonintuitive snippet in order to show the problems inherent in unclear code, in the example I was looking at. I got curious as to the result, and fretted over it until Zaxo laid it out for me.