[英]How to pipe stdin into a perl script that is looking for input as the only parameter?
This question was necessitated out of laziness on my part, because I have dozens of scripts that are executed in the simple structure: 就我而言,这个问题是出于懒惰所必需的,因为我有许多以简单结构执行的脚本:
perl my_script.pl my_input_file
...and the output is printed to stdout. ...并且输出被打印到stdout。 However, now I realize that I have certain situation in which I would like to pipe input into these scripts. 但是,现在我意识到,在某些情况下,我想将输入传递给这些脚本。 So, something like this: 因此,如下所示:
perl my_script.pl my_input_file | perl my_next_script.pl | perl third_script.pl > output
Does anyone know of a way to do this without recoding all of my scripts to accept stdin instead of a user-defined input file? 有谁知道一种无需重新编码所有脚本即可接受stdin而不是用户定义的输入文件的方式吗? My scripts look for the filename by a statement like this: 我的脚本通过如下语句查找文件名:
open(INPUT,$ARGV[0]) || die("Can't open the input file");
Thanks for any suggestions! 感谢您的任何建议!
使用-
作为文件名
perl my_script.pl my_input_file | perl my_next_script.pl - | perl third_script.pl - > output
mpapec has provided the simplest solution. mpapec提供了最简单的解决方案。 I would like to recommend the diamond operator: <>
. 我想推荐钻石操作员: <>
。
In a script where you would do 在您将要执行的脚本中
open my $fh, "<", $ARGV[0] or die $!;
while (<$fh>) {
...
You can use the diamond operator to replace most of that code 您可以使用菱形运算符替换大部分代码
while (<>) {
...
The file handle name will be ARGV
if you use argument file names, or STDIN
if not. 如果使用参数文件名,则文件句柄名称将为ARGV
否则将为STDIN
。 The file name will be found in $ARGV
. 文件名将在$ARGV
找到。
This operator invokes a behaviour where Perl looks for input either from file name arguments, or from standard input. 此运算符会调用Perl从文件名参数或标准输入中查找输入的行为。
Which means that whether you do 这表示您是否
inputpipe | script.pl
or 要么
script.pl inputfile.txt
The diamond operator will take the input just fine. 菱形运算符将很好地接受输入。
Note: Your open
statement is dangerous. 注意:您的open
声明很危险。 You should use three argument open with explicit mode, and lexical file handle. 您应该使用以显式模式打开的三个参数,以及词汇文件句柄。 The die
statement connected to it should contain the error variable $!
连接到它的die
语句应包含错误变量$!
to provide information about why the open failed. 提供有关打开失败原因的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.