jay
jay

Reputation: 79

Perl parse in command line input file

I would like to parse in input file using command line. I ran as below but I am getting error (could not open filename) when I ran as below: Is my code wrong or what I type on the commandline is incorrect?

commandline> perl script.pl FILENAME1.TXT

Below is my code to parse in input file:

my $filename = <STDIN>;
open (my $file, '<', $filename) or die "could not open file '$filename': $!";
my $str = do {local $/; <$file>};
close $file;

Upvotes: 1

Views: 1037

Answers (2)

brian d foy
brian d foy

Reputation: 132832

Perl's command line arguments show up in the variable @ARGV.

my( $filename ) = @ARGV;

However, Perl also has the special ARGV filehandle the opens the files you specify on the command line

while( <ARGV> ) { ... }

Even better, ARGV is the default filehandle:

while( <> ) { ... }

And, ARGV includes standard input if you didn't specify any arguments. That means that last while works in either of these calls:

% perl script.pl filename.txt

% perl script.pl < filename.txt

In your program, you read from STDIN, which is a different thing. That's standard input and is not related to the command line arguments. That's the data you send to the program after its running. For example, you might prompt for the filename:

print "Enter the filename: ";
my $filename = <STDIN>;
chomp( $filename );

Upvotes: 2

ekalin
ekalin

Reputation: 1012

You're trying to read $filename from standard input, when it's an argument to the program. You probably want something like

my $filename = $ARGV[0]

Upvotes: 3

Related Questions