更簡單的方法將是一個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