dominic7 has asked for the wisdom of the Perl Monks concerning the following question:

Hello Perl Monks, and thanks for any input you have to share.

I have a perl script that I want to launch at the boot up of my system. I need the script to wait for a timed duration waiting for input, and if no input is received, then it will just exit. Basically "Press any key in the next 10 seconds to invoke script"

I know how to grab user input from the command line, I just havn't figured out how to make it wait for only a limited duration.

Thank in advance.

Replies are listed 'Best First'.
Re: Timed wait for input
by BrowserUk (Patriarch) on Oct 22, 2005 at 19:47 UTC

    use Term::ReadKey; ReadMode 4; if( my $key = ReadKey 10 ) { ReadMode 0; ## Do stuff } ReadMode 0; exit; ## Do nothing.

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      Ahh! Wonderful. You sir are both a gentleman and a scholar.
Re: Timed wait for input
by GrandFather (Saint) on Oct 22, 2005 at 21:02 UTC

    A version that does the timeout as well:

    use warnings; use strict; use Term::ReadKey; my $key; my $start = time (); local $| = 1; print "Press a key: "; while (not defined ($key = ReadKey(-1))) { last if time () - $start > 10; } print defined $key ? "\nGot key $key\n" : " No key after 10 seconds";

    Perl is Huffman encoded by design.
Re: Timed wait for input
by Joost (Canon) on Oct 23, 2005 at 01:02 UTC

      Forgive me if I am incorrect, but if you added more code that needed executing after the "your input was" printout, your script there would still be forced to quit after 10 seconds, as you do not reset the alarm in your code. Here's how I'd throw it together:

      #!/usr/bin/perl -w $| = 1; use strict; my $answer = 'n'; eval { local $SIG{ALRM} = sub { die("timed out\n"); }; print "Invoke script? (y/n) "; alarm(10); chomp( $answer = <STDIN> ); alarm(0); # reset the alarm so it won't go off later }; # user entered text other than 'y' or else the 10s is up if ($@ eq "timed out\n" or lc($answer) ne 'y') { die("No positive answer. Aborting execution.\n"); } # some other error blew within the eval - best to die() elsif ($@) { die($@); } # we got the 'y' answer, so now we continue: print "Executing remainder of script.\n";