Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Perl's Getopt::Long parse arguments I don't define ahead of time?

I know how to use Perl's Getopt::Long, but I'm not sure how I can configure it to accept any "--key=value" pair that hasn't been explicitly defined and stick it in a hash. In other words, I don't know ahead of time what options the user may want, so there's no way for me to define all of them, yet I want to be able to parse them all.

Suggestions? Thanks ahead of time.

like image 661
accelerate Avatar asked Dec 01 '22 08:12

accelerate


2 Answers

The Getopt::Long documentation suggests a configuration option that might help:

pass_through (default: disabled)
             Options that are unknown, ambiguous or supplied
             with an invalid option value are passed through
             in @ARGV instead of being flagged as errors.
             This makes it possible to write wrapper scripts
             that process only part of the user supplied
             command line arguments, and pass the remaining
             options to some other program.

Once the regular options are parsed, you could use code such as that provided by runrig to parse the ad hoc options.

like image 153
Jon Ericson Avatar answered Dec 05 '22 00:12

Jon Ericson


Getopt::Long doesn't do that. You can parse the options yourself...e.g.

my %opt;
my @OPTS = @ARGV;
for ( @OPTS ) {
  if ( /^--(\w+)=(\w+)$/ ) {
    $opt{$1} = $2;
    shift @ARGV;
  } elsif ( /^--$/ ) {
    shift @ARGV;
    last;
  }
}

Or modify Getopt::Long to handle it (or modify the above code to handle more kinds of options if you need that).

like image 33
runrig Avatar answered Dec 05 '22 00:12

runrig