Hi guys,

A friend of mine had just asked an interesting question about increment, decrement operators which led to my query.

What should be the output of
perl -le '$a = 10; $a++ + $a--'

It should be 21 instead of 20 because if I were to think how the calculation would be done - convert to postfix, push operands on stack till operator is encountered, when operator encountered, pop out 2 operands and perform operation and push result onto stack:

  1. Push value of $a - 10 on stack
  2. Increment $a by 1 - 11
  3. Push value of $a - 11 on stack
  4. Increment $a by 1 - 12
  5. Pop out 10, 11 perform addition

A similar explanation can be done for:

perl -le '$a = 10; $a++ + $a--'
perl -le '$a = 10; $a++ + $a-- + $a-- + $a--'

Can you guys please tell me how would the postfix calculation progress in case of

perl -le '$a = 10; print $a++ + ++$a;'
and
perl -le '$a = 10; print ++$a + $a++;'

I don't know why the result of ++$a + $a++ turned out to be 23.

Thanks for going through,


In reply to Prefix and postfix increment/decrement operator query by saurabh.hirani

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.