【问题标题】:Perl Term::ReadKey don't wait for newlinePerl Term::ReadKey 不要等待换行符
【发布时间】:2010-06-16 15:30:16
【问题描述】:

在 perl 脚本中,我试图在不阻塞且不回显输入的字符的情况下接受输入(脚本正在生成输出,我希望使用“热键”来改变其行为)。

我已经使用了

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

但是一旦用户键入任何内容,脚本就会停止,直到输入换行符。我希望按字符处理输入,而无需等待换行符。

【问题讨论】:

  • 使用命令提示符在 Windows XP SP3 上的 ActivePerl 5.10.0 Build 1004 下工作正常。你是在使用 Cygwin 和 ActivePerl(危险的组合!)还是 Linux?
  • 这里也一样。程序在输入第一个字符后退出。这是你想要的吗?

标签: perl


【解决方案1】:

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

#!/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;
}

【讨论】:

    【解决方案2】:

    我打算将此作为对您自己的“答案”的评论,但我决定需要更多空间。

    cbreak 等同于原始模式,除了 cbreak 不拦截 ctrl-c、ctrl-z 等控制序列。它们都一次收集一个字符。两种模式之间的行为差​​异不是问题的根源。如果 Chas 的解决方案符合您的预期,那么问题很可能与您在 #process input 行中编辑的内容有关。我已经评论说,如果我用一些基本的东西填充它,你的原始脚本可以正常工作,所以我可以看到它正在工作。例如,一个小的修饰:

    use strict;
    use warnings;
    use Term::ReadKey;
    
    my ($char, $input, $pause_time);
    ReadMode("cbreak");
    
    # Collect all characters typed into $input
    # and quit when '#' is typed.
    
    $input = '';
    while ($char = ReadKey($pause_time)) {
        last if $char eq '#';
        $input .= $char;
    }
    
    print "$input\n";
    

    我没有必要在这结束时按“输入”,这样做不会有任何作用(除了将回车符扔到$input 并弄乱字符串)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      • 2013-04-11
      • 2013-11-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多