I'm surprised everyone is attributing the weird results to the order in which Perl operators evaluate their arguments. Perl doesn't have a weird evaluation order. It does things left-to-right as you would expect. Even if it did, it wouldn't sufficiently describe the outputs above.
The order in which arguments are evaluated is not specified as a feature, sure, but it's not like Perl is trying to be smart and do things in different orders each time. It reserves the right to do so, but as far as I know it does not. Also, I do not think it splits up the atomic operations
$i++ or
++$i into smaller bits, as the C optimizer might be doing, but I don't know how to check for sure. My hunch is because the increment operator is "magic" while +=1 is not.
I can't speak to what happens in C. But the real weirdness in Perl comes from the fact that the pre-increment operator returns an alias to $i (post-increment returns a plain old value). So in some of these examples, Perl evaluates the first ++$i, which returns an alias. The second increment operator changes $i. Because the first value is an alias to $i, its value also gets changed in this step before the addition operator acts on it. That is why ++$i + ++$i returns a value that is 4 greater than $i+$i: both increment operations increase both operands.
Under this interpretation and left-to-right evaluation, you can fully describe the behavior of all of these expressions.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.