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

Problem with ReadKey

by jimhenry (Acolyte)
on Nov 04, 2010 at 12:22 UTC ( [id://869446]=perlquestion: print w/replies, xml ) Need Help??

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.

Replies are listed 'Best First'.
Re: Problem with ReadKey
by liverpole (Monsignor) on Nov 04, 2010 at 13:04 UTC
    Hi jimhenry, To try to help you, I thought I would run your program and see how the execution differs from what's expected.

    I quickly realized that you omit any of the code in the main program.

    Well that shouldn't take me too much more work, I'll just see what you wrote (something about text files), and see if I can cobble together something small that calls slow_print.

    Then I looked at slow_print, and saw that it depends on an externally defined array called @paras, an external variable $rewrap_margin, and at least two external subroutines, rewrap and handle_keystroke.  (By "external", I mean external to what you gave us; maybe in the main program or some library?).

    My point is, I've now lost interest.  There are plenty of other questions where the poster is giving enough information for me to get to the fun stuff; the actual sleuthing of the problem.  To do that with your code one has to anticipate the definitions of two other data structures and two other subroutines, as well as guess how you might have called this subroutine.  Sorry, but that's work!

    Please consider providing a small, standalone program which runs on its own, and illustrates the problem.  Then I'll be glad to come back and take a look, knowing that I can dive right into solving the problem.


    s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
      I apologize for the partial, unrunnable code in my post; I shouldn't post when sleep-deprived and frustrated. If I had taken the time to figure out a minimal script that reproduces the problem, I could have asked a much more specific question -- which I'll do now. The sample script provided by jethro worked fine on my system. I then tried to figure out what was the salient difference between his script and mine, and quickly remembered that my script was (because of the huge number of text files it might need to handle) reading a long list of filenames from stdin rather than the command line. It's normally run in a pipe from a find command, like so:
      find $HOME -name \*.txt | textual-slideshow.pl $*
      It slurps the filenames from standard input, then reads random sample paragraphs from some of them, prints random paragraphs a line at a time, and repeats. My simplified version that's partway between jethro's script and mine looks like this:
      #! /usr/bin/perl use Term::ReadKey; use Time::HiRes qw(time); my @slurp_stdin = <>; ReadMode 3; while (1) { my $key; my $wait_until = time + 3; while ( time < $wait_until ) { $key = ReadKey( -1 ); if ( defined $key ) { print STDERR "keystroke $key\t"; } } print "Something\n"; }
      And it has the same problem as my script, not surprisingly. The problem clearly has to do with running in an environment where stdin is redirected. So I tried to fix that by closing STDIN and reopening it after reading the filenames. That didn't help. I tried adding an explicit STDIN argument to the ReadMode and ReadKey calls; that didn't help either. This is what I've got now, and it also has the same problem as my original script or the above modification of jethro's script:
      #! /usr/bin/perl -w use Term::ReadKey; use Time::HiRes qw(time); my @slurp_stdin = <STDIN>; close STDIN; open STDIN, "-"; while (1) { my $key; my $wait_until = time + 3; while ( time < $wait_until ) { ReadMode 3, STDIN; # 'noecho'; $key = ReadKey( -1, STDIN ); if ( defined $key ) { print STDERR "keystroke $key\t"; } ReadMode 0, STDIN; } print "Something\n"; }
      This repeatedly prints "Something"; but when I press keys, I don't get the "keystroke (key value)" message, only the value of the key. My full original script is at http://jimhenry.conlang.org/scripts/textual-slideshow.zip.

        open STDIN, "-"; is just reopening STDIN with the standard input, which is still redirected. I don't think that you can get at the terminal output that easy.

        Just remove the redirection and use the backticks operator `find $HOME -name \*.txt` or File::Find inside your perl script to get at the filenames. No redirection, no problem

Re: Problem with ReadKey
by jethro (Monsignor) on Nov 04, 2010 at 12:55 UTC
    Worked fine on Suse Linux 11.3 64bit. Here my test script:
    #!/usr/bin/perl use Term::ReadKey; use Time::HiRes qw(time); ReadMode 3; # 'noecho'; while (1) { my $key; my $wait_until = time + 3; while ( time < $wait_until ) { $key = ReadKey( -1 ); if ( defined $key ) { print STDERR "keystroke $key\t"; } } print "Something\n"; }

    Be prepared to type in perl -e 'use Term::ReadKey; ReadMode 1;' blindly after executing the script to gt a working terminal again ;-)

    Maybe some security feature (SELinux or AppArmor) gets in the way on your machine

      Be prepared to type in perl -e 'use Term::ReadKey; ReadMode 1;' blindly after executing the script to gt a working terminal again ;-)
      or reset

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2024-04-20 00:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found