【问题标题】:How to: cat text | ./script.pl如何:猫文字 | ./script.pl
【发布时间】:2016-05-30 14:45:31
【问题描述】:

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

script.pl sn-p before(工作正常):

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

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

script.pl sn-p after(仅以交互方式工作):

#!/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;
}

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

【问题讨论】:

  • 如果你想从 STDIN 读取,你需要从 STDIN 读取。您可以将行为基于my $interactive = !@ARGV &amp;&amp; -t STDIN;
  • 问题标题中无用使用 Cat 的经典示例。见en.wikipedia.org/wiki/Cat_%28Unix%29#Useless_use_of_cat
  • 你需要决定你想从哪里读取:如果你使用readline,那么它总是从/dev/tty读取。如果您使用&lt;&gt; 或标准输入,它可能会也可能不会。

标签: perl readline


【解决方案1】:

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

use warnings;
use strict;

use Term::ReadLine;

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

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

现在

回声“你好\n那里”|脚本.pl

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

Term::ReaLine 本身没有太多细节,但这是页面上列出的其他模块的前端。他们的页面有更多的信息。另外,我相信它的使用在其他地方都有介绍,例如在旧的 Cookbook 中。

【讨论】:

    猜你喜欢
    • 2012-02-08
    • 1970-01-01
    • 2021-04-30
    • 2020-01-09
    • 2014-08-29
    • 2019-12-31
    • 2021-07-26
    • 2016-11-23
    相关资源
    最近更新 更多