English 中文(简体)
How do I use GetOptions to get the default argument?
原标题:
  • 时间:2009-11-13 16:31:19
  •  标签:
  • perl

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?





相关问题
Why does my chdir to a filehandle not work in Perl?

When I try a "chdir" with a filehandle as argument, "chdir" returns 0 and a pwd returns still the same directory. Should that be so? I tried this, because in the documentation to chdir I found: "...

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 ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

Where can I find object-oriented Perl tutorials? [closed]

A Google search yields a number of results - but which ones are the best? The Perl site appears to contain two - perlboot and perltoot. I m reading these now, but what else is out there? Note: I ve ...

热门标签