perl - 如何在不打印换行符的情况下使用 Term::ReadLine 读取用户输入?

标签 perl readline

当用户按下 Enter 时,如何使用 Term::ReadLine 读取用户输入而不打印换行符?

我想这样做的原因是因为我想从屏幕底部的提示中读取用户输入(如 lessvim) .目前,按 Enter 会导致屏幕向下滚动,这可能是个问题。此外,我想避免此时不得不诉诸于 ncurses

设置 $term->Attribs->{echo_control_characters}0undefoff 似乎没有工作。

#!perl
use Term::ReadLine;
use Term::ReadKey;
my $term = new Term::ReadLine ('me');
$term->ornaments(0);
$term->Attribs->{echo_control_characters} = 0;
print STDERR "\e[2J\e[s\e[" . ( ( GetTerminalSize() ) [1] )  . ";1H";  # clear screen, save cursor position, and go to the bottom;
my $input = $term->readline('> ');
print STDOUT "\e[uinput = $input\n";   # restore cursor position, and print

我可以使用 Term::ReadKeycbreak 作为读取模式来做到这一点:

#!perl
use Term::ReadKey;
ReadMode 'cbreak';
my ( $k, $input );
print STDERR "> ";
while ( defined ( $k = ReadKey 0 ) and $k !~ /\n/ )
{
  $input .= $k;
  print STDERR $k;
}
print STDOUT "input = $input\n";
ReadMode 'restore';

但那样我就无法使用 Term::ReadLine 功能,例如历史记录、完成和行编辑。

最佳答案

您可以设置rl_getc_function 以在打印之前拦截回车,如this 所示。问题。以下对我有用:

use strict;
use warnings;
BEGIN {
    $ENV{PERL_RL} = "Gnu";
}
use Term::ReadLine;
use Term::ReadKey;

my $term = Term::ReadLine->new('me');
my $attr = $term->Attribs;
$term->ornaments(0);
$attr->{getc_function} = sub {
    my $ord = $term->getc($attr->{instream});
    if ( $ord == 13 ) {  # carriage return pressed
        $attr->{done} = 1;
        return 0;
    }
    return $ord;
};
print STDERR "\e[2J\e[s\e[" . ( ( GetTerminalSize() ) [1] )  . ";1H";
my $input = $term->readline('> ');
print STDOUT "\e[uinput = $input\n";   # restore cursor position, and print

关于perl - 如何在不打印换行符的情况下使用 Term::ReadLine 读取用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71189620/

相关文章:

php - 使用带有 readline 的 PHP 读取用户命令行输入,但 bash 不是默认 shell

r - 在 rMarkdown 中使用 readline(prompt = "")

perl - 如何让 CPAN 测试人员加载一个先决条件的开发版本?

perl - 向数组散列添加新值的简写

perl - 将 CruiseControl 转换为 Hudson

r 不允许在我的 while() 循环中进行 100 次迭代

perl - 如何在 mac 下用 perl 刷新文件?

perl - 如何在Perl中制作动画加载标志?

c++ - Readline:如何在双选项卡上列出所有自动完成匹配项?

python - Python自动解析数据