我正在試圖製作一個程序來模擬雜貨故事中的一行。 如果輸入了a,它允許用戶添加名稱。 如果輸入c,則模擬離開該線路的人員。 如果輸入p,則會打印名稱列表。 如果輸入q,則退出。在我的代碼中遇到perl無限循環的問題
我的代碼只是導致無限循環,我不知道爲什麼。每次我嘗試輸入值時,它都會讀取無效輸入並且不會退出。我不確定其他東西是否正常工作,但這不是我需要幫助的。
$choice="";
$name;
@line=();
print "\n";
print "Choose an option:\n";
print "a: Add person to end of line\n";
print "c: Call the next person in line\n";
print "p: Print the list of people in line\n";
print "q: Quit\n";
print "\n";
while ($choice ne "q") {
print "Your choice:";
$choice = <>;
print "\n";
if($choice eq "a") {
print "Enter name:";
$name = <>;
push(@line,$name);
}
elsif ($choice eq "c") {
shift(@line);
}
elsif ($choice eq "p") {
for ($i=0;$i<=scalar(@line);$i++) {
print (@line[$i]);
}
}
elsif ($choice eq "q") {
exit;
}
else {
print "Invalid option";
}
}
您是否聽說過['chomp'](http://perldoc.perl.org/functions/chomp.html)? – ephemient 2012-04-19 04:26:16
請'使用嚴格'。也許可以將'for'循環重寫爲'for $ person(@line){print「$ person \ n」; }''這樣可以避免循環條件中的off-by-one錯誤以及使用數組切片('@line [$ i]'),其中簡單元素訪問('$ line [$ i]')是意。 – pilcrow 2012-04-19 05:05:29