如何在经过一定时间后(毫秒,我正在使用Time::HiRes
模块)获取用户输入,但如果时间过去且没有输入则没有任何反应。具体来说,我会逐字打印一个问题,直到STDIN出现中断。为此,程序在继续打印之前等待一小段时间,如果没有中断则打印下一个字。我该怎么做,或者是更好的选择。谢谢一堆。我的初始程序看起来像这样:
use Time::HiRes qw/gettimeofday/;
$initial_time = gettimeofday();
until (gettimeofday() - $a == 200000) {
;
if ([<]STDIN[>]) { #ignore the brackets
print;
}
}
答案 0 :(得分:1)
查看Time::HiRes中的ualarm
功能。
它与alarm的工作方式类似,因此请查看有关如何使用它的示例。
这是一个完整的例子:
#!/usr/bin/perl
# Simple "Guess the Letter" game to demonstrate usage of the ualarm function
# in Time::HiRes
use Time::HiRes qw/ualarm/;
my @clues = ( "It comes after Q", "It comes before V", "It's not in RATTLE",
"It is in SNAKE", "Time's up!" );
my $correctAnswer = "S";
print "Guess the letter:\n";
for (my $i=0; $i < @clues; $i++) {
my $input;
eval {
local $SIG{ALRM} = sub { die "alarm\n" };
ualarm 200000;
$input = <STDIN>;
ualarm 0;
};
if ($@) {
die unless $@ eq "alarm\n"; # propagate unexpected errors
# timed out
}
else {
# didn't
chomp($input);
if ($input eq $correctAnswer) {
print "You win!\n";
last;
}
else {
print "Keep guessing!\n";
}
}
print $clues[$i]."\n";
}
print "Game over man!\n";