Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Readkey with timer using Glib

by zentara (Archbishop)
on Jan 26, 2008 at 17:26 UTC ( [id://664462]=CUFP: print w/replies, xml ) Need Help??

Hi, this is a little snippet, that allows realtime single key control of a script, with Glib. It is just a basic outline. I post it, because it is tricky. If the readkey sub is in the main script, it will block the timer(rest of script) from functioning. With the readkey in the thread, the main script can process whatever you setup, and still watch for keycontrol. It might be useful in some situations..... like a panic button!!!! :-)
#!/usr/bin/perl use warnings; use strict; use Glib; use Term::ReadKey; use threads; #use threads::shared; $|++; ReadMode('cbreak'); # works non-blocking if read stdin is in a thread my $count = 0; my $thr = threads->new(\&read_in)->detach; my $main_loop = Glib::MainLoop->new; my $timer = Glib::Timeout->add (1000, \&timer_callback, undef, 1 ); # can also have filehandle watches #my $watcher; #$watcher = Glib::IO->add_watch( fileno( $pty ), ['in', 'hup'], \&call +back); $main_loop->run; ReadMode('normal'); # restore normal tty settings sub timer_callback{ #do stuff $count++; print "\n$count\n"; return 1; } sub read_in{ while(1){ my $char; if (defined ($char = ReadKey(0)) ) { print "\t\t$char->", ord($char),"\n"; #process key presses here #if($char eq 'q'){exit} if(length $char){exit} # panic button on any key :-) } } } __END__

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (7)
As of 2024-03-28 22:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found