如何:猫文本 | ./script.pl
How to: cat text | ./script.pl
我最近开始使用 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
用于所有未来的 I/O。请注意,该模块具有检索输入和输出文件句柄($term->OUT
和 $term->IN
)的方法,因此您可以稍后更改 I/O 的位置。
Term::ReaLine
本身没有太多细节,但这是页面上列出的其他模块的前端。他们的页面有更多信息。此外,我相信其他地方也涵盖了 this 的用途,例如在 Cookbook
.
中
我最近开始使用 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
用于所有未来的 I/O。请注意,该模块具有检索输入和输出文件句柄($term->OUT
和 $term->IN
)的方法,因此您可以稍后更改 I/O 的位置。
Term::ReaLine
本身没有太多细节,但这是页面上列出的其他模块的前端。他们的页面有更多信息。此外,我相信其他地方也涵盖了 this 的用途,例如在 Cookbook
.