How do I use GetOptions to get the default argument?
开发者_如何学运维I've read the doc for GetOptions
but I can't seem to find what I need... (maybe I am blind)
What I want to do is to parse command line like this
myperlscript.pl -mode [sth] [inputfile]
I can use the -mode
part, but I am not sure how to get the [inputfile]. Any advice will be appreciated.
You don't use GetOptions
for this task. GetOptions
will simply parse options for you and leave everything that is not an option in @ARGV
. So after calling GetOptions
simply look at @ARGV
for any file names passed on the command line.
Anything not handled by GetOptions is left in @ARGV
. So you would likely want something like
use Getopt::Long;
my %opt
my $inputfile = 'default';
GetOptions(\%opt, 'mode=s');
$inputfile = $ARGV[0] if defined $ARGV[0];
GetOptions
will leave any arguments that it didn't parse, in the @ARGV
variable. So you can just loop over the @ARGV
variable.
use Getopt::Long;
my %opt;
GetOptions(
\%opt,
'mode=s'
);
for my $filename (@ARGV){
parse( $filename, \%opt );
}
There is another option, you can use the special <>
argument callback option.
use Getopt::Long qw'permute';
our %opt;
GetOptions(
\%opt,
'mode=s',
'<>' => sub{
my($filename) = @_;
parse( $filename, \%opt );
}
);
This is useful if you want to be able to work on multiple files, but use different options for some of them.
perl test.pl -mode s file1 file2 -mode t file3
This example will set $opt{mode}
to s
, then it will call parse
with file1
as an argument. Then it will call parse
with file2
as the argument. It will then change $opt{mode}
to t
, and call parse
with file3
, as an argument.
The command line arguments that don't begin with -
will still be in @ARGV
, won't they?
精彩评论