Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic round robin in Perl difference between (++ / +1)

Tags:

perl

Recently I was trying to make a simple round robin with Perl , and I found a behaviour that I don't understand clearly.

Here the behaviour:

my $a = {index => 0};
for (0 .. 10) {
    $a->{index} = ($a->{index}++) % 2;
    warn $a->{index};
}

The output of this code will be:

0,0,0,..,0

But if I do the "same" code replacing $a->{index}++ by $a->{index}+1 , the round robin will be fine, example

my $a = {index => 0};
for (0 .. 10) {
    $a->{index} = ($a->{index}+1) % 2;
    warn $a->{index};
}

The output will be:

1,0,1,0,1,0,1,0...

Someone can explain me the difference between ++ / +1 in this case? I find this really "ugly", because if I don't assign the result to any variable in the case "++" the code will work as expected unless I put the sum inside ().

This code will do a round robin correctly:

my $a = {index => 0};
for (0 .. 10) {
    warn $a->{index}++ % 2;
}

With () in the sum, the code will output: 1,2,3,4,5,6,7,8,9

my $a = {index => 0};
for (0 .. 10) {
    warn ($a->{index}++) % 2;
}
like image 469
jordivador Avatar asked Aug 20 '15 14:08

jordivador


1 Answers

$a->{index}+1 returns $a->{index}+1, while
$a->{index}++ returns $a->{index} before it was changed.
++$a->{index} returns $a->{index}+1, but it makes no sense to use it in that expression since it needlessly changes $a->{index}.


$a->{index} = ($a->{index}+1) % 2;

  1. Say $a->{index} is initially 0.
  2. $a->{index}+1 returns 1.
  3. Then you assign 1 % 2, which is 1 to $a->{index}.

$a->{index} = $a->{index}++ % 2;

  1. Say $a->{index} is initially 0.
  2. $a->{index}++ sets $a->{index} to 1 and returns 0 (the old value).
  3. Then you assign 0 % 2, which is 0 to $a->{index}.

Options:

$a->{index} = ( $a->{index} + 1 ) % 2;
if ($a->{index}) {
   ...
}

or

$a->{index} = $a->{index} ? 0 : 1;
if ($a->{index}) {
   ...
}

or

$a->{index} = !$a->{index};
if ($a->{index}) {
   ...
}

or

if (++$a->{index} % 2) {
   ...
}

or

if ($a->{index}++ % 2) {
   ...
}

Note that the last two options leaves an ever-increasing value in $a->{index} rather than 0 or 1.

Note that the last two options differ in whether the condition will be true or false on the first pass.

like image 142
ikegami Avatar answered Oct 21 '22 07:10

ikegami