我正在试图制作一个程序来模拟杂货故事中的一行。 如果输入了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