I’m very new to Perl and have been given an assignment that is a simple guessing game where the user is given 8 chances to guess a number between 1 and 100. I keep getting the error mentioned above and cannot figure it out.
Here’s my code:
use Modern::Perl;
my ($guess,$target,$counter);
$target = (int rand 100) + 1;
while ($guess < $target)
{
chomp ($guess=<>);
print "Enter guess $counter: ";
$counter++;
if ($guess eq $target) {
print "\nCongratulations! You guessed the secret number $target in $counter";
}
elsif ($guess > $target) {
print "\nYour guess, $guess, is too high.";
}
elsif ($guess < $target) {
print "\nYour guess, $guess, is too low.";
}
else {
print "You lose. The number was $target.";
}
}
Your code suffers a few issues. Here is my code, using a different approach:
Example usage:
(all other corner cases (too many guesses, non-numbers as input) work as expected)
What did I do differently?
while (1)loop would have worked as well.I use proper comparision operators. Perl scalars come in two flavours: stringy and numeric:
sayfunction prints the string likeprint, but appends a newline. This removes akward\ns at the beginning or the end of the string. It makes reading code easier.