1

I have a script which gets executed, but I require a loop which tells the process to sleep for 20-30 secs whilst a user runs a different test.

Once that test is completed then the user presses Enter to continue from where the script was halted. If Enter is not pressed within the 20-30 second period the script is to continue to run without user input.

I tried the following code but it pauses the script indefinitely – it does not continue after 20 secs, but it also does not accept Enter.

use Term::ReadKey;
ReadMode 4;
do {
    sleep 20; 
} until ( defined( $key = ReadKey(-1) ) );
ReadMode 0;

2 Answers 2

1

Try a while loop instead of do{}

#!usr/bin/perl
use strict;
use warnings;
use Term::ReadKey;

ReadMode 4;    # Turn off controls keys
my $key;

while ( !defined( $key = ReadKey(-1) ) ) {
    print "No key yet\n";
    sleep 5;
}
print "Get key $key\n";

ReadMode 0;    # Reset tty mode before exiting
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks tried the provided code, and the output keeps posting 'No Key Yet' every 5 secs, even when I press any key, the output just keeps looping with 'No Key Yet', and does not jump to the next section. Seems it is not detecting the keystrokes.
When I run this code it goes into the loop and exits it after I pressed a key. Just as intended. Which perl are you using? I tested this on Perl 5.14 on Ubuntu 13.04 64bit
Also am using Windows, and trying to obtain the keystroke from a HTML page if that helps.
Perl 5.8.7 on a UNIX environment, but calling via Windows (IE) a CGI/HTML script.
So you are writing a web application? I used the command line. Try it in windows cmd. But I don't think that Term::Readkey is suitable for inputs from CGI. Try something similar with javascript on your HTML page. If no key is pressed the request is send with predefinded parameters.
|
1

Here's some code:

use Term::ReadKey;

ReadMode(4);
my $key;
my $wait = 20;

for (my $x = 0; $x < $wait; $x++) {
if (defined ($key = ReadKey(-1))) {
        print "key pressed\n";
        break;
    }
    print "waiting for key press\n";
    sleep(1);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.