Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

how to check for keyboard input

by redss (Monk)
on Jul 21, 2005 at 03:48 UTC ( [id://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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://476702]
Approved by monkfan
Front-paged by bofh_of_oz
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (5)
As of 2024-04-24 06:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found