in reply to How to implement a timer in perl?
If you want to use an event loop system, like Tk, Gtk2, or POE, you can do a neater job. Tk or Gtk2 make it trivial, but you need to be running under X or Windows. You just setup an event to be fired after the timeout you give.#!/usr/bin/perl -w use strict; my $input = &my_stdin( prompt =>"Enter some text: ", timeout => 3, handler => \&my_alarm ); print "You entered: $input \n"; sub my_stdin { use Term::ReadKey; $| = 1; #turn buffering off so we can see our print below my %args = @_; my ($output,$key ); my $prompt = $args{'prompt'}; my $timeout = $args{'timeout'}; my $toh = $args{'handler'}; # ref to a handler $SIG{ALRM} = $toh || sub { print "Timeout\n"; exit;}; alarm($timeout); print $prompt; ReadMode 4; while(1){ if(defined($key = ReadKey(-1))){ my $val = ord $key; # 8 is backspace 10 and 13 are $output .= $key unless $val == 8 || $val == 10 || $val == 13; #echo to the screen print $key if length $output > 0; alarm($timeout); #reset the alarm #last if the user hits return last if ( $val == 10 || $val == 13); # chop one if we get a backspace if( $val == 8 ){ chop $output; print " "; print chr(8); } } } ReadMode 0; print "\n"; $output; } sub my_alarm{ print "I just died because you waited too long!\n"; exit; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How to implement a timer in perl?
by holli (Abbot) on Feb 02, 2006 at 20:44 UTC | |
|
Re^2: How to implement a timer in perl?
by redss (Monk) on Feb 02, 2006 at 21:01 UTC | |
by Anonymous Monk on Feb 19, 2015 at 06:57 UTC |