如何将stdin管道输入perl脚本,该脚本正在寻找输入作为唯一参数?

jak*_*115 11 perl stdin pipe

这个问题在我的懒惰中是必要的,因为我有几十个以简单结构执行的脚本:

perl my_script.pl my_input_file
Run Code Online (Sandbox Code Playgroud)

...并将输出打印到stdout.但是,现在我意识到我有某种情况需要将输入输入到这些脚本中.所以,像这样:

perl my_script.pl my_input_file | perl my_next_script.pl | perl third_script.pl > output
Run Code Online (Sandbox Code Playgroud)

有没有人知道如何在不重新编码我的所有脚本以接受stdin而不是用户定义的输入文件的情况下执行此操作?我的脚本通过如下语句查找文件名:

open(INPUT,$ARGV[0]) || die("Can't open the input file");
Run Code Online (Sandbox Code Playgroud)

谢谢你的任何建议!

Сух*_*й27 13

使用-的文件名

perl my_script.pl my_input_file | perl my_next_script.pl - | perl third_script.pl - > output
Run Code Online (Sandbox Code Playgroud)


TLP*_*TLP 7

mpapec提供了最简单的解决方案.我想推荐钻石运营商:<>.

在你要做的脚本中

open my $fh, "<", $ARGV[0] or die $!;
while (<$fh>) { 
    ... 
Run Code Online (Sandbox Code Playgroud)

您可以使用菱形运算符替换大部分代码

while (<>) {
    ...
Run Code Online (Sandbox Code Playgroud)

ARGV如果使用参数文件名,STDIN则文件句柄名称将是,否则.文件名将在$ARGV.中找到.

此运算符调用Perl从文件名参数或标准输入查找输入的行为.

这意味着你是否这样做

inputpipe | script.pl
Run Code Online (Sandbox Code Playgroud)

要么

script.pl inputfile.txt
Run Code Online (Sandbox Code Playgroud)

钻石操作员会很好地接受输入.

注意:您的open陈述很危险.你应该使用三个参数open with explicit mode和lexical file handle.die连接到它的语句应包含错误变量,$!以提供有关打开失败原因的信息.