perl - 如何 : cat text | ./script.pl

标签 perl readline

我最近开始使用Term::Readline,但现在我意识到cat text | ./script.pl 不起作用(无输出)。

之前的 script.pl 片段(工作正常):

#!/usr/bin/perl
use strict;
use warnings;

$| = 1;
while (<>) {
   print $_;
}

之后的 script.pl 片段(仅以交互方式工作):

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

$| = 1;
my $term = Term::ReadLine->new('name');
my $input;
while (defined ($input = $term->readline('')) ) {
   print $input;
}

我能做些什么来保持这种行为(打印这些行)?

最佳答案

您需要将其设置为使用您想要的输入和输出文件句柄。文档没有详细说明,但构造函数采用字符串(用作名称),或该字符串和 globs 作为输入和输出文件句柄(两者都需要)。

use warnings;
use strict;

use Term::ReadLine;

my $term = Term::ReadLine->new('name', \*STDIN, \*STDOUT);

while (my $line = $term->readline()) {
    print $line, "\n";
}

现在

echo "hello\nthere" | script.pl

hello 打印两行和 there , 而 scipt.pl < input.txt打印出文件的行 input.txt .在此之后正常 STDINSTDOUT将被模块的 $term 使用对于所有 future 的 I/O。请注意,该模块具有用于检索输入和输出文件句柄($term->OUT$term->IN)的方法,因此您可以稍后更改 I/O 的位置​​。

Term::ReaLine 本身没有太多细节,但这是页面上列出的其他模块的前端。他们的页面有更多信息。此外,我相信其他地方也涵盖了它的用途,例如在旧的 Cookbook 中。 .

关于perl - 如何 : cat text | ./script.pl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37528446/

相关文章:

xml - 使用 XML::Parser 解析大型 XML 文件时如何查看进度?

bash - Bash : how do you "reset" the search in Cygwin? 中的 Control-r 反向搜索

ruby-on-rails - Windows 下的 Rails 3 readline 问题

python - readline() 在源文件中跳过行

c# - 完成对 SerialPort.ReadLine() 的调用

perl - 如何在最新的 perl 上安装额外的 perl 模块(事件状态)

multithreading - 循环使用线程

perl - 如何在我的父类中创建一个对象,但在 Perl 中将它祝福到我的子类中?

perl - 浏览目录的最佳方式是什么?

linux - bash 中的有效输入