更简单的方法将是一个while
loop。
use strict;
use warnings;
print "Hello, I've thought of a number, do you know what number it is?\n";
sleep (1);
my $int = int(rand (10)) + 1;
print "Try and guess, type in a number between 1 and 10!\n";
while (my $div = <STDIN>) {
chomp $div;
if ($div < $int) {
print "The number I though of is higher than $div, try again?\n";
}
elsif ($div > $int) {
print "The number I though of is lower that $div, try again?\n";
}
else {
print "Amazing, you've guessed mt number\n";
last;
}
}
虽然(双关语意),你的代码已经很不错(您正在使用strict
和warnings
,有没有语法错误,耶为!)有一些事情我变了,一些在那里我会建议改进。
但首先,让我们看看循环。只要条件成立,该程序就会保留在while
循环中。由于用户可以输入的所有内容(甚至是空行)被Perl认为是真的,这是永远的。这是好的,因为有条件退出循环。它位于if
的else
部分。 last
声明告诉Perl退出循环。如果else
未执行,则会返回到while
块的起始位置,用户必须重试。永远。
的变化我做: - 你不需要$i
因为你没有使用它 - 您使用了三个独立的if
语句。由于只有三个条件之一可以在这种情况下是正确的,我合并他们到一个 - 不需要的括号()
与print
建议: - 您应该为您的变量,他们做了什么,而不是他们是。 $int
不是一个好名字。我会去$random
,甚至$random_number
。如果您稍后必须返回代码,则详细程度非常重要。 - 有一个function called say
,您可以使用use feature 'say';
启用。它增加了say "stuff"
,相当于print "stuff\n"
。
编辑:
如果你想补充一点,不直接与用户输入到其他一些条件,你可以添加其他if
。
while (my $div = <STDIN>) {
chomp $div;
if ($div eq 'quit') {
print "You're a sissy... the number was $int. Goodbye.\n";
last;
}
if ($div < $int) {
print "The number I though of is higher than $div, try again?\n";
}
elsif ($div > $int) {
print "The number I though of is lower that $div, try again?\n";
}
else {
print "Amazing, you've guessed mt number\n";
last;
}
}
您还可以添加一个检查以确保用户输入了一个数字。如果输入单词或字母,您当前的代码将会产生警告。要做到这一点,你需要一个正则表达式。请在perlre上阅读。 m//
是与=~
一起工作的match operator。 \D
匹配任何不是数字(0到9)的字符。 next
步骤while
块的其余部分,并开始检查while
条件。
while (my $div = <STDIN>) {
chomp $div;
if ($div =~ m/\D/) {
print "You may only guess numbers. Please try again.\n";
next;
}
# ...
}
因此,完整的检查手段“看东西的用户输入,如果有任何东西比一个数字都抱怨,让他再试一次”。
你没有循环,虽然你似乎知道你需要一个循环。你想知道什么?循环的语法? – Ingo 2013-03-16 12:24:25
我要去尝试直到循环,看看我是否需要这些。我想是的。 – joesh 2013-03-16 13:19:19
我最近在[codereview](http://codereview.stackexchange.com/a/23556/21609)上展示了一个功能丰富的“猜我的号码”的实现。你可能想要在那里寻找灵感。 – amon 2013-03-16 13:38:24