Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: logic problem with perl game

by PeterPeiGuo (Hermit)
on Dec 04, 2010 at 01:34 UTC ( [id://875307] : note . print w/replies, xml ) Need Help??


in reply to logic problem with perl game

1) As a starter, for those if conditions, instead of using "and", use &&. "and" has a very low precedence.

2) Your else is only paired with the last if. Chain those if's together with if/else if/else.

Peter (Guo) Pei

Replies are listed 'Best First'.
Re^2: logic problem with perl game
by mynameisG (Novice) on Dec 04, 2010 at 01:47 UTC

    So you mean like this?

    if(($response eq "arrow" && $correctryhm eq "sparrow")) { $correctryhm=param('correctryhm'); $response=param('response'); $win=param('win'); $win=$win+1; } elsif(($response ne "arrow" && $correctryhm eq "sparrow")) { $correctryhm=param('correctryhm'); $response=param('response'); $lose=param('lose'); $lose=$lose+1; } if(($response eq "axe" && $correctryhm eq "wax")) { $correctryhm=param('correctryhm'); $response=param('response'); $win=param('win'); $win=$win+1; } elsif(($response ne "axe" && $correctryhm eq "wax")) { $correctryhm=param('correctryhm'); $response=param('response'); $lose=param('lose'); $lose=$lose+1; } if(($response eq "shield" && $correctryhm eq "field")) { $correctryhm=param('correctryhm'); $response=param('response'); $win=param('win'); $win=$win+1; } elsif(($response ne "shield" && $correctryhm eq "field")) { $correctryhm=param('correctryhm'); $response=param('response'); $lose=param('lose'); $lose=$lose+1; } if(($response eq "spear" && $correctryhm eq "tear")) { $correctryhm=param('correctryhm'); $response=param('response'); $win=param('win'); $win=$win+1; } elsif(($response ne "spear" && $correctryhm eq "tear")) { $correctryhm=param('correctryhm'); $response=param('response'); $lose=param('lose'); $lose=$lose+1; }

    and then have that last else statement at the end

      Like the following, and you need to use && not "and" (unless you get the precedence straight by using ()):

      if(($response eq "arrow" && $theword eq "sparrow")) { ... } elsif(($response eq "axe" && $theword eq "wax")) { ... } elsif(($response eq "shield" && $theword eq "field")) { ... } elsif(($response eq "spear" && $theword eq "tear")) { ... } else { }

      Peter (Guo) Pei

        PeterPeiGuo, your doubled parentheses serve no function. Perhaps you meant to contain each condition in parentheses? But even so, your advice only complicates the code, by losing operater-precedence contrast.

        To mynameisG, regarding the original post: your original conditional code is perfect -- easy to read and does what it says. The reason "and" and "or" exist as low-precedence operators is for that very reason. You don't need to add parentheses (especially ones that do nothing) when "and" and "or" always have lower precedence than comparison operators like "eq" and ">=".