Limbic~Region has asked for the wisdom of the Perl Monks concerning the following question:

All: Having had minimal success in the past with other languages, I am seeking advice before trying to re-invent the wheel. I would like my program to request input from a user, but default to a hard coded value if it does not receive the response in a specified amount of time (no need for high precision here). Links to docs, links to nodes, sample code, alternatives are all welcomed. Thanks L~R

Replies are listed 'Best First'.
Re: default value after timeout
by fglock (Vicar) on Aug 29, 2002 at 19:57 UTC

    alternatives are all welcomed

    perldoc perlipc shows how to setup a timeout; you might try to modify it for your needs (untested).

    sub getinput { my $default = shift; my $value; eval { local $SIG{ALRM} = sub { die "alarm clock restart" }; alarm 10; # your code here, read <STDIN> $value = ... alarm 0; }; if ($@ and $@ !~ /alarm clock restart/) { return $default } return $value; }
      Thanks - I found a very similar piece of code in the Camel book 3rd edition, which I was able to modify.
      #!/usr/bin/perl -w use strict; my $value; my $timedout; sub timedout { $value = "default"; $timedout = 1; die; } eval { local $SIG{ALRM} = 'timedout'; alarm 10; print "Please enter the value - you have 10 seconds\n"; chomp ($value = <STDIN>); alarm 0; }; alarm 0; if ( $timedout ) { print "You timed out - setting value to $value\n"; } else { print "You entered $value within the 10 second time frame\n"; }
      I am new to Perl, but I would have thought this had come up more. I am still interested in other solutions, so keep them coming!
Re: default value after timeout
by stephen (Priest) on Aug 29, 2002 at 20:43 UTC
    You might want to check out Term::ReadLine::Gnu. It allows access to the GNU Readline Library, which allows you to specify a timeout.

    stephen

Re: default value after timeout
by gnu@perl (Pilgrim) on Aug 30, 2002 at 20:29 UTC
    You may want to look at IO::Select. Here is an excerpt from the perldoc:
    NAME IO::Select - OO interface to the select system call SYNOPSIS use IO::Select; $s = IO::Select->new(); $s->add(\*STDIN); $s->add($some_handle); @ready = $s->can_read($timeout); @ready = IO::Select->new(@handles)->read(0);