How can I allow undefined options when parsing args with Getopt

佐手、 提交于 2019-11-30 04:47:27

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

$ cat my_script.pl
#!/usr/local/bin/perl5.8 -w

use Getopt::Long;
Getopt::Long::Configure("pass_through");
use Data::Dumper;
my %args;
GetOptions(\%args, "foo") or die "GetOption returned 0\n";
print Data::Dumper->Dump([\@ARGV],["ARGV"]);

$ ./my_script.pl -foo -WHATEVER          
$ARGV = [
          '-WHATEVER'
        ];

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

#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;
use Data::Dumper;

my $foo;
my $result = GetOptions ("foo"   => \$foo);
print Dumper([ $foo, \@ARGV ]);

Then calling:

my_script.pl --foo -- --WHATEVER

gives:

$VAR1 = [
          1,
          [
            '--WHATEVER'
          ]
        ];

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!

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

GetOptions('foo' => \$foo) 
    or die "Whups, got options we don't recognize!";

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!