我是一个Perl新手,试图找出为什么我的直到条件在基本猜数游戏中从未评估为真。
#!/usr/bin/perl
# Ex 10-1
use warnings;
$num = int(1 + rand 100);
print "\$num is $num\n"; # Debug
print "I'm thinking of a number between 1 and 100. What number is it?\n";
until (chomp($guess = <STDIN>) == $num) {
print "\$guess is $guess\n"; # Debug
if ($guess =~ /\A\s*(quit|exit)?\s*\z/) {
print "Exiting.\n";
exit 0;
} elsif ($guess =~ /\D/) {
print "Invalid input. ";
} else {
($guess < $num) ? (print ("Too low. ")) : (print ("Too high. "));
}
print ("Guess again.\n");
}
print ("Congrats! You guessed the number.\n");
exit 0;
以下是执行的一个例子:
$ ./ex1
$num is 4
I'm thinking of a number between 1 and 100. What number is it?
5
$guess is 5
Too high. Guess again.
3
$guess is 3
Too low. Guess again.
4
$guess is 4
Too high. Guess again.
将$ guess与$ num进行比较,当输入4时,$ guess等于$ num,满足测试条件。然而它仍然进入循环并使其达到打印的最终(默认)结果并且太高了。&#34;
我还尝试在chomp($ guess =)周围添加另一组括号,但这并没有帮助。
为什么会这样?
答案 0 :(得分:6)
chomp
返回删除的字符数,而不是chomp
之后的修改后的参数,因此您不应该在循环条件中使用返回值。
chomp(my $guess = <STDIN>);
until ($guess == $num) {
...
chomp($guess = <STDIN>);
}