How can I mix command line arguments and file names for <> in Perl?

Consider the following dumb Perl program:

 $firstarg = $ARGV[0]; print $firstarg; $input = <>; print $input; 

I run it from the terminal like:

 perl myprog.pl sample_argument 

And get this error:

 Can't open sample_argument: No such file or directory at myprog.pl line 5. 

Any ideas why this is so? When it gets to <> is it trying to read from a (nonexistent) file, "sample_argument" or something else? And why?

+6
source share
3 answers

<> is an abbreviation for "read from files specified in @ARGV , or if @ARGV empty, then read from STDIN ". In your program, @ARGV contains the value ("sample_argument") , and so Perl tries to read from this file when you use the <> operator.

You can fix this by clearing @ARGV before going to the <> line:

 $firstarg = shift @ARGV; print $firstarg; $input = <>; # now @ARGV is empty, so read from STDIN print $input; 
+12
source

See the man perlio page, which is partially read:

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

If you want STDIN, use STDIN, not <> .

+8
source

By default, perl consumes command line arguments as input files for <> . After you use them, you must use them yourself with shift;

+1
source

All Articles