www.webdeveloper.com
Results 1 to 4 of 4

Thread: Help with operator precedence

  1. #1
    Join Date
    Mar 2012
    Posts
    29

    Help with operator precedence

    Hi
    I am having a bit of a problem working out operator precedence in the follow expression, the output of which is 0.
    I realize ++$value2 is incremented immediately so both ++$value2s should now contain 3,
    and $value1-- is not decremented immediately so contains 8, which should make the expression
    8 % 3 * 3 which when run mysteriously returns 6, 8 / 3 has remainder 2, 2 * 3 = 6, I had a look at a perl operator
    precedence chart, which said * is before % this would make the expression 8 % 9

    Code:
    $value1 = 8;
    $value2 = 2;
    $value3 = $value1-- % $value2 * ++$value2;
    print ($value3);
    
    output: 0
    I also tried to see how it calculated by enclosing the expression in double quotes which returned the following -

    Code:
    print "$myvar1-- % $myvar2 * ++$myvar2";
    
    output:  8-- % 2 * ++282

  2. #2
    Join Date
    Oct 2007
    Location
    Vienna, Austria
    Posts
    392
    There's a neat module called B::Deparse, that can show you how exactly the perl interpreter understands your code. I saved the code in a file called precedence.pl and called the following line and getting the following output:
    Code:
    perl -MO=Deparse,-p precedence.pl 
    ($value1 = 8);
    ($value2 = 2);
    ($value3 = ((($value1--) % $value2) * (++$value2)));
    print($value3);
    This means you get 8%2, which is 0 times whatever, so obviously 0; Only after the multiplication is carried out, the increment takes place, though the incremented value is used. So you have ((8%2)*3)

    The quote approach can of course not work, because you only get the variables interpolated and not the operators.
    Last edited by Sixtease; 01-24-2014 at 05:34 AM. Reason: stupid emoticons

  3. #3
    Join Date
    Oct 2007
    Location
    Vienna, Austria
    Posts
    392
    By the way, the difference between saying $foo++ vs ++$foo is not that ++$foo is somehow incremented sooner or "immediately". It merely means that the expression returns the original or the incremented value respectively.

  4. #4
    Join Date
    Mar 2012
    Posts
    29
    Hi
    Many thanks for replying!
    As suggested I downloaded the module from cpan as it wasn't available in the Activeperl package manager.
    I am sure it will be invaluable to me. Also the syntax used must be exact perl -MO=Deparse,-p precedence.pl
    the first time I ran it I mistakenly included a space between the , - and got totally different output.

    Best regards Maxwell

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles