If I have a command line like:
my_script.pl -foo -WHATEVER
My script knows about --foo
, and I want Getopt to set variable $opt_foo
, but I don't know anything about -WHATEVER
. How can I tell Getopt to parse out the options that I've told it about, and then get the rest of the arguments in a string variable or a list?
An example:
use strict;
use warnings;
use Getopt::Long;
my $foo;
GetOptions('foo' => \$foo);
print 'remaining options: ', @ARGV;
Then, issuing
perl getopttest.pl -foo -WHATEVER
gives
Unknown option: whatever remaining options:
I think the answer here, sadly though, is "no, there isn't a way to do it exactly like you ask, using Getopt::Long, without parsing @ARGV on your own." Ether has a decent workaround, though. It's a feature as far as most people are concerned that any option-like argument is captured as an error. Normally, you can do
to capture/prevent odd options from being passed, and then you can correct the user on usage. Alternatively, you can simply pass through and ignore them.
You need to configure "pass_through" option via
Getopt::Long::Configure("pass_through");
Then it support actual options (e.g. stuff starting with "-" and without the special "--" delimiter to signify the end of "real" options).
Here's perldoc quote:
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.Here's an example
Aren't the remaining (unparsed) values simply left behind in
@ARGV
? If your extra content starts with dashes, you will need to indicate the end of the options list with a--
:Then calling:
gives:
PS. In MooseX::Getopt, the "remaining" options from the command line are put into the
extra_argv
attribute as an arrayref -- so I'd recommend converting!