Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: how to check for keyboard input

by tlm (Prior)
on Jul 21, 2005 at 04:15 UTC ( [id://476708]=note: print w/replies, xml ) Need Help??


in reply to how to check for keyboard input

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

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

    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

        s/&/\\&/g; Otherwise, safe_exit is immediately called. Also, I tend to wrap sub's similar to safe_exit in lexical blocks and prevent them from being called more than once. e.g.

        use Term::ReadKey; { my $called = 0; sub safe_exit { print "safe_exit called $called times before\n"; return if $called++; # disconnect from DB, etc. (things that should only be done on +ce) ReadMode 'normal'; print "Exiting safely\n"; print "exit(@_)\n" if @_; exit @_; } } $SIG{$_} = \&safe_exit for qw/INT QUIT __DIE__/; END { safe_exit(); } ReadMode 'cbreak'; print "Entering loop. Try: kill -INT $$, to see that I exit safely.\nH +it 'x' to see me die.\n"; while (1) { next unless defined(my $key = ReadKey); print "In the loop, got: $key\n"; last if $key eq 'q'; die "with this error message" if $key eq 'x'; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://476708]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-03-29 13:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found