Term::ReadKey within a loop halts the enclosing loop
I have a while loop that works. I want to capture keystrokes within that loop but the ReadKey routine halts the enclosing loop. What am I doing wrong?
#!/usr/bin/perl
use strict;
use w开发者_Go百科arnings;
use Term::ReadKey;
my $char;
while(1 < 5) {
print time . "\n";
while(1) {
ReadMode('raw');
$char = ReadKey(0);
print "Got $char\n";
}
sleep(5);
}
It's not exactly clear from your question and the code you posted what you're trying to accomplish. On the one hand the question sounds as if you're trying to get a non-blocking read. If that's the case, you might want something more like this for your inner loop:
while(1) {
ReadMode('cbreak');
my $char = ReadKey(-1);
next unless defined($char);
print "Got $char\n";
last if $char eq "\t";
}
ReadKey(-1) sets up a non-blocking read, which means it doesn't wait for input; it just tells you what the input is, if any, and then moves on to the next iteration. If there's no input it returns undef. You'll notice I switched the ReadMode to 'cbreak', for testing purposes, so that I could easily hit CTRL-C when I was ready to terminate. Hitting tab would also terminate in this example code. Since the ReadMode() is set to -1, for non-blocking, we just keep looping.
Your code also had the issue of "while( 1 < 5 )
". What good do you think that's doing for you? 1 is always less than 5, so that loop will never terminate. If you really want a neverending loop, just say while(1)
so we know you know what you mean. On the other hand, I considered the possibility that you really meant to say something like while( $i++ < 5 )
so that you would get at least five iterations of the outer loop.
One final note. Whatever "ReadMode" you set, you really should call "ReadMode('restore')
" before exiting the program, or your terminal may remain 'goofy'. For example, on mine, without putting a ReadMode('restore');
at the end of the program, hitting enter wouldn't give me a new line in my terminal. This module doesn't seem to clean up after itself on termination, so you have to do it explicitly.
You should also look over the documentation for Term::ReadKey. Most of what I've discussed here is right there for the reading if you but look.
精彩评论