如何:cat text | ./script.pl

时间:2016-05-30 14:45:32

标签: 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;
}

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

1 个答案:

答案 0 :(得分:2)

您需要将其设置为使用所需的输入和输出文件句柄。文档没有拼写出来,但是构造函数接受一个字符串(用作名称),或者用于输入和输出文件句柄的字符串和glob(需要两者)。

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

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

Term::ReaLine本身并没有太多细节,但这是页面上列出的其他模块的前端。他们的页面有更多的信息。此外,我相信其他地方也会使用此功能,例如在好的旧Cookbook中。