views:

200

answers:

2

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?

A: 

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.

lugte098
I specifically want to call perl inside Bash script. ($input) is Perl right?
neversaint
whoops, yeah! now it should work in bash. Make sure that you type foo=`cut -f1,2 file1.txt` and not foo = `cut -f1,2 file1.txt`
lugte098
+5  A: 

<> is special: It returns lines either from standard input, or from each file listed on the 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") ...
edgar.holleis
This has bitten many perl users. This was designed so as to mimic the syntax of several basic unix commands; so that, por example, this program works (roughly) the same as "cat": while(<>) {print;}
leonbloy