Reputation: 137
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
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
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