开发者

Perl standard input with argument inside Bash

I want to have such pipe in bash

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

Now in myperl.pl it has content like this

开发者_高级运维
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? 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?


<> 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.

In your case you know that you want to read your data from <stdin>, so just use that instead of <>:

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 <>:

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:

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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜