2009/11/3 Majian <jian...@gmail.com>:
> Hi ,all:
>
>  When I test the increment operator in Perl and  find   a question :
>
> The question is :
> #!/usr/bin/perl
> use warnings;
>
> my $i = 1;
> print  ++$i  + ++$i, "\n";
>
> The above code prints  out  the answer 6 .
> But in the other language  the anser is 5 ,
>
> So  I don't understand the reason why it is
>
>
> Would someone give me some  options ?

>From perldoc perlop:

"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
behaviour. Avoid statements like:

   1. $i = $i ++;
   2. print ++ $i + $i ++;

Perl will not guarantee what the result of the above statements is."

The problem is that you are trying to modify the same variable twice
in the same statement. The solution is: don't do that then!

Write it separately, to explicitly state what you mean:

my $i = 1;
$i++;
$i++;
print $i + $i, "\n"; # prints 6

or alternatively

my $i = 1;
my $j = ++$i;
print ++$i + $j, "\n"; # prints 5

Philip

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to