http://qs1969.pair.com?node_id=869446

jimhenry has asked for the wisdom of the Perl Monks concerning the following question:

I have a script that reads text files listed on the command line and slowly prints random paragraphs from them to stdout. I want to modify it so that instead of simply sleep, print, sleep until ctrl-break, it traps keystrokes and slows down or speeds up printing, turns on and off wrapping, quits, pauses, displays help, etc., based on the key pressed.

Theoretically Term::ReadKey should do this, from what I've read in various pages around the web and threads on this forum. However, this code and several variations I've tried are not working:

use Term::ReadKey; use Time::HiRes qw(time); #....... sub slow_print { my $subscript = shift; my $para = $paras[ $subscript ]; if ( $rewrap_margin ) { $para = &rewrap( $para ); } my @lines = split /\n/, $para; foreach ( @lines ) { print $_ . "\n"; my $thispause = $pause_len * length $_; ReadMode 3; # 'noecho'; print STDERR "should be sleeping for $thispause secs\n" if $deb +ug; my $key; my $wait_until = time + $thispause; while ( time < $wait_until ) { $key = ReadKey( -1 ); if ( defined $key ) { print STDERR "keystroke $key\t"; &handle_keystroke( $key ); } } } print "\n\n"; }

Whether I tap a key intermittently or hold something down indefinitely, $key never gets defined and handle_keystroke() never gets called; and echo isn't getting turned off, either, whether I pass 3 or 'noecho' to ReadMode. I'm using Perl v5.10.0 ("built for i486-linux-gnu-thread-multi") on Ubuntu 8.10 in a gnome-terminal (2.24.1) window.

I've tried several different things: doing a four-arg select to sleep before the call to ReadKey instead of a while loop checking highres time(); passing different mode values to ReadMode; passing 0 to ReadKey instead of -1; checking for

while ( (not defined ($key = ReadKey( -1 ) ) ) and (time < $wait_until +) ) { }

as an empty loop... nothing seems to change its behavior, except for passing $this_pause to ReadKey, which theoretically should make ReadKey sleep that many seconds or until a key is pressed, but actually causes the script to scroll lines nonstop without a pause.