If it were evaluated right to left, then the answer would negative four

No, it's a per-operator thing, as + and - are different operators, and their precedence defines they should be evaluated left-to-right. This is done by implicit parentheses:

2;0 juerd@ouranos:~$ perl -MO=Deparse,-p -e'sub one { 1 } sub two { 2 +} sub three { 3 } print one() - three() + two()' sub one { 1; } sub two { 2; } sub three { 3; } print(((one() - three()) + two()));
(I had to use these subs, because Perl optimizes 1-2+3 to a literal 0 :)

So we have these calculation:
  1. 1 - 3 = -2
  2. answer ( = -2 ) + 2 = 0
But which are evaluated first? the 1 or the 3? The -2 or the 2? It becomes clear when you test the operators one by one (or so I thought):
2;0 juerd@ouranos:~$ perl -le'sub foo { print "foo"; return 1 } sub ba +r { print "bar"; return 2 } print foo + bar' bar foo 1 2;0 juerd@ouranos:~$ perl -le'sub foo { print "foo"; return 1 } sub ba +r { print "bar"; return 2 } print foo && bar' foo bar 2
So I decided to test a lot of operator this way, but found out that everything was evaluated left-to-right, but not if I left out the parens. Why did my first test print bar before foo then? Because I didn't print foo() + bar() but did print foo( +bar() ).

So that still doesn't solve our mistery...

- Yes, I reinvent wheels.
- Spam: Visit eurotraQ.


In reply to Re: Re: $i=$i++ by Juerd
in thread $i=$i++ by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.