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?
As Rohit answered, the solution is to add the
$before theb. The exact reason it doesn’t print"Why not?"but prints"WTF” is this: when you give thebwithout the$sign (and withoutuse strict;in force), Perl treats thebas 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, soWTFis printed and not"Why not?"