Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

how to check for keyboard input

by redss (Monk)
on Jul 21, 2005 at 03:48 UTC ( #476702=perlquestion: print w/replies, xml ) Need Help??
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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://476702]
Approved by monkfan
Front-paged by bofh_of_oz
What's the matter? Cat got your tongue?...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (2)
As of 2017-08-17 04:57 GMT
Find Nodes?
    Voting Booth?
    Who is your favorite scientist and why?

    Results (281 votes). Check out past polls.