我最近开始使用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;
}
我可以做些什么来保留这种行为(打印行)?
您需要将其设置为使用所需的输入和输出文件句柄。 文档没有详细说明,但构造函数要么采用字符串(用作名称),要么采用该字符串和 glob 作为输入和输出文件句柄(两者都需要)。
use warnings;
use strict;
use Term::ReadLine;
my $term = Term::ReadLine->new('name', *STDIN, *STDOUT);
while (my $line = $term->readline()) {
print $line, "n";
}
现在
回声"你好那里" |script.pl
打印带有 hello
和 there
的两行,而scipt.pl < input.txt
打印出文件input.txt
的行。在此之后,模块的$term
将使用相同的正常STDIN
和STDOUT
进行所有未来的 I/O。 请注意,该模块具有检索输入和输出文件句柄($term->OUT
和$term->IN
)的方法,因此您可以稍后更改 I/O 的位置。
Term::ReaLine
本身没有太多细节,但这是页面上列出的其他模块的前端。他们的页面包含更多信息。另外,我相信它的用途在其他地方有介绍,例如在好的旧Cookbook
中。