Perl standard input with argument inside Bash

I want to have a pipe like this in bash

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

      

Now 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 can't the Perl script recognize the parameter passed through bash? Namely, breaking the code with this message:

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

      

What's the correct way to do this so that my Perl script can receive standard input and parameter at the same time?

+2


source to share


3 answers


<>

is special: it returns lines from either standard input or from each file specified on the command line. Therefore, command line arguments are interpreted as filenames for opening and returning lines. Hence the error is msgs that it cannot open the file foo

.

In your case, you know you want to read your data from <stdin>

, so just use instead <>

:

while(<stdin>)

      



If you want to preserve the functionality of the optional input of input files on the command line, you need to remove the argument foo

from @ARGV

before using <>

:

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

      

+6


source


To get an argument before perl tries to open it as input, use the block BEGIN

:

This one doesn't work :

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

      



speaking 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

      

+1


source


Try:

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

      

I am assuming you are trying to pipe the output from the cut command as the "foo" argument to the myperl.pl script.

0


source







All Articles