超时perl中的用户输入

use*_*726 4 unix perl 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';
    }
Run Code Online (Sandbox Code Playgroud)

警报超时正在按预期工作,但是我希望在倒计时后每秒减少一次额外的打印声明(比如10秒说"10 ... 9 .. 8 ..还有")任何人都可以请求如何获取此功能与超时一起嵌入.

谢谢

Сух*_*й27 6

# 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';
}
Run Code Online (Sandbox Code Playgroud)

  • @RobEarl它将以9开始打印.在其他情况下,空格应该胜过"print"\ r $ count"行的其余部分." (3认同)