perl - 超时 perl 中的用户输入

标签 perl unix timeout

我想提示用户输入,一段时间后,如果没有响应,脚本必须退出。我有这个代码

eval {
        local $SIG{ALRM} = sub { die "timeout getting the input \n" };
        alarm 5;
        $answer = <STDIN>;
        alarm 0;
        chomp $answer;
    };
    if ($@) {
        #die $@ if $@ ne "timeout getting the input\n";
        $answer = 'A';
    }

警报超时按预期工作,但我希望在每秒递减类似于倒计时后有一个额外的打印语句(例如 10 秒说“10 ...9 ..8 ..等)”
任何人都可以帮助如何将此功能与超时一起嵌入。

谢谢

最佳答案

# disable output buffering
$| = 1;

my $answer;
eval {
        my $count = 10;
        local $SIG{ALRM} = sub {
          # print counter and set alaram again
          if (--$count) { print "$count\n"; alarm 1 } 
          # no more waiting
          else { die "timeout getting the input \n" }
        };
        # alarm every second
        alarm 1;
        $answer = <STDIN>;
        alarm 0;
        chomp $answer;
};
if ($@) {
        #die $@ if $@ ne "timeout getting the input\n";
        $answer = 'A';
}

关于perl - 超时 perl 中的用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24010716/

相关文章:

perl - 在 moose 默认值中使用 localtime

apache - 无法加载 'C:/Apache/Perl/site/lib/auto/Apache2/ModSSL/ModSSL.dll'

shell - tcsh - 以破折号 (-) 开头的命令行参数

python - 为什么代码在 python 中停止在 input() 处 - 有什么好处?

linux - ElasticSearch 中的超时更改不起作用

Perl关闭套接字

perl - 如何优雅地调用名称保存在变量中的 Perl 子例程?

Git服务器不随便显示最新推送的文件

linux - 如何根据指定的行数拆分 CSV 文件?

java - jdbc4 通信异常