Im trying to make a simple heads or tails game in perl. But no matter if the answer is correct or not it tells me i lose. Am i just missing something fundamental here? Any help would be appreciated.
print "Heads or tails?";
$guess = <>;
print "Your guess is ",$guess;
$randNum = int(rand(10));
if ($randNum % 2 ==0){
$answer = "heads";
} else {
$answer = "tails \n";
}
print "The right answer is ", $guess;
$c = $guess eq $answer;
if ($c == 1){
print "you win!";
} else {
print "you lose";
}
CodePudding user response:
$c = $guess eq $answer;
This will take into consideration the exact string in your answer, and your answer has a newline half the time, and your guess both times. Also you have a space after 1 answer.
For example, lets say you guess "heads", then your $guess
string will be:
$guess = "heads\n"; # newline added when reading with <>
Your answer will be either of these
$answer = "heads";
$answer = "tails \n";
So lets compare those...
# start end
# |heads\n|
# |heads|
# |tails \n|
As you can see, the only possible way for eq
to be true is if you guessed "tails "
, with an included space.
What you need to do is to clean up your input, and not have any newlines in your answer.
For example:
chomp(my $guess = <>); # remove newline from input
...
$answer = "heads";
...
$answer = "tails";
You can also strip whitespace and make the string the same case.
$guess =~ s/\s//g; # strip whitespace
$guess = lc($guess); # make lowercase
Also, note that writing Perl code without these two pragmas make your life excessively hard, so always include them:
use strict;
use warnings;
CodePudding user response:
When you read the answer, you also get the final newline. You need to remove it from the input before comparing. You'll see that if you put quotes around the output:
print "Heads or tails? ";
my $guess = <>;
print "Your guess is '$guess'\n";
This will remove all spaces from the input, which should make sense in your case:
$guess =~ s/\s*//mg;
Unrelated, but may confuse you --- you have
print "The right answer is ", $guess;
where it should probably be
print "The right answer is ", $answer;
Finally, for good style, declare your variables and always put this at the top of your script:
use strict;
use warnings;