【问题标题】:Waiting for a defined period of time for the input in Perl在 Perl 中等待定义的时间段输入
【发布时间】:2015-11-29 02:05:19
【问题描述】:

怎么说呢

等待输入 10 秒
如果没有识别出输入
打印一些东西

在 Perl 中?

【问题讨论】:

标签: linux perl


【解决方案1】:

IO::Selectcan_read 超时。

#!/usr/bin/env perl

use strict;
use warnings;
use IO::Select;

my $select = IO::Select->new();
$select->add( \*STDIN );

my $input = "NONE";
if ( $select->can_read(10) ) {
    $input = <STDIN>;
}

print "Got input of $input\n";

【讨论】:

    【解决方案2】:

    你可以使用alarm()

    use strict;
    use warnings;
    
    sub timeout {
    
      my ($f, $sec) = @_;
    
      return eval {
        local $SIG{ALRM} = sub { die };
        alarm($sec);
        $f->();
        alarm(0);
        1;
      };
    }
    
    my $text;
    my $ok = timeout(sub{ $text = <STDIN>; }, 10);
    
    if ($ok) {
      print "input: $text";
    }
    else {
      print "timeout occurred\n";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-25
      相关资源
      最近更新 更多