trala has asked for the wisdom of the Perl Monks concerning the following question:

It seems this should be easy, but I've been banging my head against the wall... I want to call my perl script with 1 parameter and an output from another script, like this: perl script1.pl | perl script2.pl 1 Then I want to store the parameter in a variable and parse the piped input, like so:
$num = @ARGV[0]; while (<>) { (parser algorithm) } print ("$result");
Well, it doesn't work. I get the error "Can't open 1: no such file or directory" and the parsed output is as if no data has been processed. I assume this is because the 1 is going into <> along with the piped input. Is there some way I can get it out of there before going into my while loop? Also, a curiosity is that the following code behaves slightly differently:
$num = @ARGV[0]; printf (<>); while (<>) { (parser algorithm) } print( "$result" )
I still get the error message, but now the parser output is correct. I could just redirect stderr to null and my output is perfect ;) but I'd like to know the "right" way to do this.

Replies are listed 'Best First'.
Re: parameters and piped input
by Bob9000 (Scribe) on Aug 10, 2005 at 17:21 UTC

    You can strip the args you want out of @ARGV before using <>:

    $num = shift @ARGV; while (<>) { ... process data ... }

    Or if you don't want any automatic processing of file arguments, you can just read from <STDIN> instead of <>.

Re: parameters and piped input
by ikegami (Patriarch) on Aug 10, 2005 at 17:57 UTC

    Since you want to read from standard input, you could use STDIN:

    num = @ARGV[0]; while (<STDIN>) { (parser algorithm) } print ("$result");
Re: parameters and piped input
by sk (Curate) on Aug 10, 2005 at 20:14 UTC
    As Bob9000 pointed out you need a shift before you can use the diamond operator.

    This is from  perldoc perlop http://perldoc.perl.org/perlop.html

    The null filehandle <> is special: it can be used to emulate the behavior of sed and awk. Input from <> comes either from standard input, or from each file listed on the command line. Here's how it works: the first time <> is evaluated, the @ARGV array is checked, and if it is empty, $ARGV[0] is set to "-", which when opened gives you standard input. The @ARGV array is then processed as a list of filenames.

    If you are thinking of lot of command line options in the future check out

    Getopt::Std and Getopt::Long