http://qs1969.pair.com?node_id=476702

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

Hello monks!

My program needs to process data and periodically poll for keyboard input.
What function can I use on the third line to check if a key was pressed, without waiting forever for input?

while (1) { sleep(1); if key was pressed { # HELP, how can I check? print "$key was pressed\n"; exit if $key eq 'q'; } do stuff... }

Replies are listed 'Best First'.
Re: how to check for keyboard input
by Tanktalus (Canon) on Jul 21, 2005 at 04:14 UTC

    Check out Term::ReadKey. Its synopsis almost exactly shows what you want.

Re: how to check for keyboard input
by tlm (Prior) on Jul 21, 2005 at 04:15 UTC

    use strict; use warnings; use Term::ReadKey; my $done; while ( 1 ) { sleep 1; ReadMode( 'cbreak' ); if ( defined ( my $key = ReadKey( -1 ) ) ) { # input waiting; it's in $key $done = $key eq 'q'; } ReadMode( 'normal' ); exit if $done; # do stuff... }

    Update: Thanks to Tanktalus for pointing out the exit bug. Also thanks to bobf for pointing out typo in comment. Both fixed.

    the lowliest monk

      Warning: you need to set the readmode back to normal before exiting. So don't just exit on 'q' - do something to get the terminal back into its regular state.

      sub safe_exit { ReadMode('normal'); exit(@_); } # ... safe_exit if $key eq 'q'; # ...
        To be extra sure the terminal is in a sane state after the program exits, the safe_exit routine could be hooked in some other places, too, e.g.
        $SIG{'INT'} = \&safe_exit; $SIG{'QUIT'} = \&safe_exit; $SIG{__DIE__} = \&safe_exit; END { safe_exit(); }
        --- Update: oops, references added, as benizi pointed out below