Perl 用户输入直到时间过去

Perl 用户输入直到时间过去,perl,Perl,在经过一定的时间(毫秒,我正在使用time::HiRes模块)之前,我如何获取用户输入,但是如果时间过去了,没有输入,那么什么也不会发生。具体来说,我会逐字逐句地打印一个问题,直到标准输入中断。为此,程序在继续打印前等待一小段时间,如果没有中断,则打印下一个字。我如何才能做到这一点,或者是一个更好的选择。非常感谢。我的初始计划如下所示: use Time::HiRes qw/gettimeofday/; $initial_time = gettimeofday(); until (gettime

在经过一定的时间(毫秒,我正在使用
time::HiRes
模块)之前,我如何获取用户输入,但是如果时间过去了,没有输入,那么什么也不会发生。具体来说,我会逐字逐句地打印一个问题,直到标准输入中断。为此,程序在继续打印前等待一小段时间,如果没有中断,则打印下一个字。我如何才能做到这一点,或者是一个更好的选择。非常感谢。我的初始计划如下所示:

use Time::HiRes qw/gettimeofday/;
$initial_time = gettimeofday();
until (gettimeofday() - $a == 200000) {
        ;
        if ([<]STDIN[>]) { #ignore the brackets
                print;
        }
}
使用时间::雇佣qw/gettimeofday/;
$initial_time=gettimeofday();
直到(gettimeofday()-$a==200000){
;
如果([]){#忽略括号
印刷品;
}
}

查看中的
ualarm
功能

它的工作原理与此类似,因此请查看如何使用它的示例

下面是一个完整的示例:

#!/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";
#/usr/bin/perl
#简单的“猜字母”游戏,演示ualarm函数的使用
#及时雇佣
使用时间::雇用qw/ualarm/;
我的@cruels=(“它在Q之后”、“它在V之前”、“它不在摇铃中”,
“它在蛇里”,“时间到了!”);
我的$correctAnswer=“S”;
打印“猜字母:\n”;
对于(我的$i=0;$i<@线索;$i++){
我的$input;
评估{
本地$SIG{ALRM}=sub{die“alarm\n”};
200000乌克兰格里拉;
$input=;
乌拉拉姆0;
};
如果($@){
死亡,除非$@eq“报警”\n;#传播意外错误
#超时
}
否则{
#没有
chomp($输入);
如果($input eq$CORPORT ANSWERK){
打印“您赢了!\n”;
最后;
}
否则{
打印“继续猜测!\n”;
}
}
打印$CLUERS[$i]。“\n”;
}
打印“游戏结束男人!\n”;

一些解决方案:使用Term::Readkey、IO::Select进行轮询,使句柄无阻塞,通过信号中断