The Unfun Cat
The Unfun Cat

Reputation: 31968

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?

Upvotes: 2

Views: 165

Answers (3)

Sundar R
Sundar R

Reputation: 14725

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?"

Upvotes: 9

Rohit Jain
Rohit Jain

Reputation: 213351

Always use use strict and use warnings.

You are using your last two b's as bareword, which will be shown as warning - "Unquoted string "b" may clash with future reserved word"

You need to change your if to: -

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

and: -

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

gives expected results.

Upvotes: 8

jaggy
jaggy

Reputation: 123

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

works over here, you forgot the $, but apearntly you already found it :)

Upvotes: 2

Related Questions