Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Question preincrement

by himik (Acolyte)
on Aug 03, 2012 at 13:37 UTC ( #985234=perlquestion: print w/ replies, xml ) Need Help??
himik has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks! I have question

my $a=1; print ++$a + $a++;

How much will this print?

shouldn't it be 4? And not 5?

I test this in PHP and there is 5

1. in the start $a is 1

2. first of all in the print is ++$a and $a become 2

3. second is $a+$a and become 4

4. third is print

5. fourth $a become 3

Thank you

I found the answer in perldoc

Note that just as in C, Perl doesn't define when the variable is incremented or decremented. You just know it will be done sometime before or after the value is returned. This also means that modifying a variable twice in the same statement will lead to undefined behavior. Avoid statements like:

$i = $i ++; print ++ $i + $i ++;

Comment on Question preincrement
Select or Download Code
Re: Question preincrement
by toolic (Chancellor) on Aug 03, 2012 at 13:42 UTC
Re: Question preincrement
by choroba (Abbot) on Aug 03, 2012 at 13:43 UTC
    Have you read the documentation?
    Note that just as in C, Perl doesn't define when the variable is incremented or decremented. You just know it will be done sometime before or after the value is returned. This also means that modifying a variable twice in the same statement will lead to undefined behavior. Avoid statements like:
    $i = $i ++; print ++ $i + $i ++;
    Does the last line look familiar?

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://985234]
Approved by marto
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (19)
As of 2014-10-30 17:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (208 votes), past polls