http://www.perlmonks.org?node_id=593014

brusimm has asked for the wisdom of the Perl Monks concerning the following question:

After a bit of looking around, I have a conflict of logic I hope we can resolve!

A: The below script was an experiment I put together. I am very NEW to Perl, & I was trying to understand the auto-increment function, and I now DO understand it. (Then I got carried away)

B: After a bit of research on Perldoc & Perlmonks, I discovered that “Perl does not define when the variable is incremented, or de-incremented” AND there are no guarantees as to the consistency of the output from one system to another. (That’s the sanity in me speaking.)

C: Barring the previous statement that this should be an unpredictable script, I have a colleague at work that can read any of these lines, and predict to me what the output will be. (The sanity just left the building again.) This prompted me try to understand the order of operations happening here. She explained it to me, and it made sense, but the next day, I can’t remember for the life of me what she said. One other item she explained was the ++$i was performed on first, then $i++. Much like multiplication before addition, as an example.

D: The script below prints out, 0 to 10. (My system is an Intel, XP based system, using ActivePerl 5.8.8, build 819) in this environment, and also under Cygwin on the same system. I am not looking to make use of this script in any way, I’m just trying to understand something here, if it is to be understood. (IE: It’s magic).

Q: How is the math being done in as much as what order preference the script is using to work on the variables to do the math and how is it being applied to create the output I’ve been seeing? I tried creating a visual matrix to better understand this, but I run into some roadblocks, mental. {I hope I have asked this in a way that makes sense.}

Thank you to anyone who can help me with what little sanity I can possibly retain.

$i = $i++; # #print "\n"; # This is a noop.. effectively being 0. print "Test 0: $i\n"; $i = 0; # $i = ++$i; # print "Test 1: $i\n"; # ++ adds 1, then $i is looked at, and ++ add +ed to it. $i = 0; # $i = $i++ + ++$i; # print "Test 2: $i\n"; $i = 0; $i = ++$i + $i++; # print "Test 3: $i\n"; # $i = 0; # $i = ++$i + ++$i; # print "Test 4: $i\n"; # $i = 0; # $i = ++$i + $i++ + $i++; # print "Test 5: $i\n"; # $i = 0; # $i = ++$i + $i++ + ++$i; # print "Test 6: $i\n"; # $i = 0; # $i = ++$i + ++$i + ++$i; # print "Test 7: $i\n"; # $i = 0; # $i = $i++ + $i++ + ++$i + ++$i ; # print "Test 8: $i\n"; # $i = 0; # $i = $i++ + ++$i + ++$i + ++$i ; # print "Test 9: $i\n"; # $i = 0; # $i = ++$i + ++$i + ++$i + $i++ ; # print "Test 10: $i\n"; # print "\n";