Search code examples
perlshort-circuitingoperation

Short circuit and giving incorrect results?


I am experiencing strange results with Perl's short circuited and, that is &&.

I am trying to solve a Project Euler problem where I want a certain number to be divisible by a list of numbers.

$b=42;

if($b%21==0 && b%2==0 && b%5==2){print "Why not?"};

Should print "Why not" as far as I can see, but keeps silent.

$b=42;

if($b%21==0 && b%2==0 && b%5==0){print "WTF?"};

Should keep silent, but prints "WTF?".

What gives?


Solution

  • As Rohit answered, the solution is to add the $ before the b. The exact reason it doesn't print "Why not?" but prints "WTF" is this: when you give the b without the $ sign (and without use strict; in force), Perl treats the b as the string "b". Then when you apply the operator % on it, since % is a numerical operator, Perl looks within the string "b" and checks whether it starts with a number. Since it doesn't, Perl takes the numerical value of "b" as 0, and then applies the mod (%) operation. 0%5 is 0 and not 2, so WTF is printed and not "Why not?"