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?

1
  • 2
    is there a special reason you are not using Perl to cut the 1st and 2nd field of file1.txt? Since you are using Perl, you can do everything in Perl, including the sorting. Commented Apr 12, 2010 at 8:49

3 Answers 3

6

<> 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") ...
Sign up to request clarification or add additional context in comments.

1 Comment

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;}
1

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

Comments

0

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.

2 Comments

I specifically want to call perl inside Bash script. ($input) is Perl right?
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.