user640527
user640527

Reputation: 93

Why does the modulus operator behave differently in Perl and PHP?

I've this PHP function which does not work for negative numbers:

function isOdd($num) 
{
   return $num % 2 == 1; 
}

but it works for positive number.

I have this Perl routine which does the exact same thing and works for negative number also

sub isOdd()
{
  my ($num) = @_;
  return $num % 2 == 1;
}

Did I make any mistake in translating the function ? or is it PHP bug ?

Upvotes: 9

Views: 1090

Answers (1)

codaddict
codaddict

Reputation: 454960

In PHP the sign of the result of x % y is the sign of dividend which is x but
in Perl it is the sign of the divisor which is y.

So in PHP the result of $num % 2 can be be either 1, -1 or 0.

So fix your function compare the result with 0:

function isOdd($num) { 
  return $num % 2 != 0; 
}

Upvotes: 21

Related Questions