我最近开始使用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
.在此之后正常 STDIN
和 STDOUT
将被模块的 $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/