简体   繁体   English

在 Bash 中带有参数的 Perl 标准输入

[英]Perl standard input with argument inside Bash

I want to have such pipe in bash我想在 bash 中有这样的管道

#! /usr/bin/bash
cut -f1,2 file1.txt | myperl.pl foo | sort -u 

Now in myperl.pl it has content like this现在在myperl.pl它有这样的内容

my $argv = $ARG[0] || "foo";

while (<>) {
 chomp;
 if ($argv eq "foo") {
  # do something with $_
 }
 else {
   # do another
 }
}

But why the Perl script can't recognize the parameter passed through bash?但是为什么Perl 脚本无法识别通过bash 传递的参数呢? Namely the code break with this message:即代码中断与此消息:

Can't open foo: No such file or directory at myperl.pl line 15.

What the right way to do it so that my Perl script can receive standard input and parameter at the same time?这样做的正确方法是什么,以便我的 Perl 脚本可以同时接收标准输入和参数?

<> is special: It returns lines either from standard input, or from each file listed on the command line. <>是特殊的:它从标准输入或从命令行中列出的每个文件返回行。 The arguments from the command line are therefore interpreted as file names to open and to return lines from.因此,来自命令行的参数被解释为要打开和返回行的文件名。 Hence the error msgs that it cannot open file foo .因此,它无法打开文件foo的错误消息。

In your case you know that you want to read your data from <stdin> , so just use that instead of <> :在您的情况下,您知道要从<stdin>读取数据,因此只需使用它而不是<>

while(<stdin>)

If you want to retain the functionality of optionally specifying input files on the command line, you need to remove argument foo from @ARGV before using <> :如果要保留在命令行上可选指定输入文件的功能,则需要在使用<>之前从@ARGV删除参数foo

my $firstarg = shift(@ARGV);
...
while (<>) {
    ...
    if ($firstarg eq "foo") ...

To get the argument before perl tries to open it as an input, use a BEGIN block:要在 perl 尝试将其作为输入打开之前获取参数,请使用BEGIN块:

This fails :失败了

cat file | perl -ne '$myarg=shift; if ($myarg eq "foo") {} else {}' foo #WRONG

saying Can't open foo: No such file or directory.Can't open foo: No such file or directory.

But this works :但这有效

cat file | perl -ne 'BEGIN {$myarg=shift}; if ($myarg eq "foo") {} else {}' foo

Try:尝试:

foo=`cut -f1,2 file1.txt`
myperl.pl $foo | sort -u

I guess that you're trying to pipe the output from the cut command as an argument "foo" to the myperl.pl script.我猜您正试图将 cut 命令的输出作为参数“foo”传送到 myperl.pl 脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM