【问题标题】:timeout a user input in perl在 perl 中超时用户输入
【发布时间】:2014-06-03 08:43:06
【问题描述】:

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

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 ..等等) 任何人都可以帮助如何将此功能与超时一起嵌入。

谢谢

【问题讨论】:

标签: perl unix timeout


【解决方案1】:
# 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';
}

【讨论】:

  • 您好,感谢您的回复。是否有可能不是将 $count 打印为 10..9..8 等等,而是只打印一个数字,即第一个 10 ,然后每秒 10 被 9 ..so 替换。?
  • @user3304726 试试print "\r$count";
  • @mpapec 不会出现打印 10、90、80、70 ... 等?
  • @RobEarl 它将从 9 开始打印。在其他情况下,空格应该超过行的其余部分 print "\r$count ";
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多