Perl Term :: ReadKey不等待换行符

tim*_*tim 7 perl

在perl脚本中,我试图接受输入而不阻塞并且不回显输入的字符(脚本正在生成输出,我希望有'热键'来改变它的行为).

我得到了使用

use Term::ReadKey;
ReadMode( "cbreak", STDIN );
if($input = ReadKey($pause_time, STDIN)){
    #process input
}
Run Code Online (Sandbox Code Playgroud)

但是一旦用户键入任何内容,脚本就会停止,直到输入换行符.我希望每个字符处理输入,而不必等待换行符.

Cha*_*ens 7

这是一个小程序,可以满足我的需求:

#!/usr/bin/perl

use strict;
use warnings;

use Term::ReadKey;

ReadMode 4;
END { ReadMode 0 }

print <<EOS;
q to quit
b to print in binary
o to print in octal
d to print in decimal
x to print in hexadecimal
EOS

my $control = "d";
my $i       = 0;
while (1) {
    #use "if" if you want to have a buffer of commands
    #that will be processed one per second  
    while (defined (my $key = ReadKey(-1))) {
        exit 0          if $key eq 'q';
        $control = $key if $key =~ /^[bodx]$/;
    }
    printf "%$control\n", $i++;
    sleep 1;
}
Run Code Online (Sandbox Code Playgroud)