Reputation: 63984
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?
Upvotes: 2
Views: 2299
Reputation: 4991
<>
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") ...
Upvotes: 6
Reputation: 14824
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
Upvotes: 1
Reputation: 2309
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.
Upvotes: 0