japan
japan

Reputation: 137

Waiting for a defined period of time for the input in Perl

What is the way to say

wait for the 10 sec for the input
if no input recognized
print something

in Perl?

Upvotes: 3

Views: 327

Answers (2)

Sobrique
Sobrique

Reputation: 53488

IO::Select and can_read with a timeout.

#!/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";

Upvotes: 3

mpapec
mpapec

Reputation: 50647

You can use 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";
}

Upvotes: 1

Related Questions