Reputation: 13
I would like Perl to check the command line to see if there were input files/arguments. Otherwise, use the default file when there are no arguments:
#!/usr/bin/perl -w
open(INPUT, "<", "./list2") || die "Couldn't open list for reading: $!\n";
while (<INPUT>)
{
# print stuff;
}
close(INPUT);
I've got the default file (list2) that will be opened, but don't know how to check for input. I'm thinking of using a conditional statement (if argument_exists then read the input from the command line; else open the default_file). Does this exist in a library in Perl, or is there a regular expression ?
Upvotes: 1
Views: 535
Reputation: 390
Since you're trying to read the file, it might make sense to check if the command line argument file exists. You can also make sure the argument is a file, not a socket or some other weird thing you're not expecting.
my @temp_array = @ARGV; #make a copy of command line arguments
@ARGV = (); #we will re-build this list
foreach (@temp_array) { #check the validity of every argument
if (-e and -f) { #-e means the path exists, -f means it's a file
push @ARGV, $_; #add this back to the @ARV list
} else {
print "Path '$_' is invalid\n";
} #/else
} #/foreach
if (!@ARGV) {
push @ARGV, './list2';
}
Upvotes: 0
Reputation: 35208
Parameters to your script are held in @ARGV
. Therefore, simply check if that array contains any values, and add your desired logic.
You can also use @ARGV
for reading from your default file like so:
#!/usr/bin/perl -w
use strict;
use warnings;
@ARGV = './list2' if ! @ARGV;
while (<>) {
# print stuff
}
Upvotes: 4