出于某种原因,奇怪的循环行为,我简单的菜单程序,奇怪的事情发生,因为ReadKey的结果()perl的 - 与ReadKey
#!/usr/local/bin/perl
use strict ;
use warnings ;
use English ;
use Term::ReadKey ;
my @available_choices = ('choice one', 'choice two', 'choice three') ;
my $array_size = scalar (@available_choices) ;
print "\nPlease make your selection from the options below:\n\n" ;
for (my $i=0, my $j=1 ; $i < $array_size ; $i++, $j++) {
print "$j) $available_choices[$i]\n" ;
}
my $key = undef ;
for (my $k=0; $k < 5; $k++) {
print "\nSelection :> " ;
$key = ReadKey();
if ((defined $key) && ($key =~ /[1-$array_size]/)) {
print "\nYou selected \"$available_choices[$key-1]\"\n" ;
last ;
}
else {
sleep 1 ;
}
}
所以,如果你运行这个简单的程序,并给予1,2,或3作为您的选择它按预期工作。如果你输入了其他东西(来触发else块),那么在ReadKey()再次接受输入之前,循环重复3或4次。这个输出最好的说明(我进入XXX,然后在“选择:>”印刷3次,我能键入YYY前):
$ ./bar.pl
Please make your selection from the options below:
1) choice one
2) choice two
3) choice three
Selection :> xxx
Selection :>
Selection :>
Selection :>
Selection :> yyy
Duh。 “ReadKey读取_key_”说明了一切。谢谢! –