我知道如何使用Perl的Getopt::很长,但我不确定我怎么能配置,以接受 任何 "--key=value"对没有明确定义,并坚持它在一散列。换句话说,我不知道未来的时间有什么选择的用户可能想要的,所以没有办法让我来定义的所有他们,但我希望能够解析他们所有。

建议?谢谢你的时间提前。

有帮助吗?

解决方案

Getopt::Long 文件建议的结构的选项,可能会有所帮助:

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.

一旦定期的选择进行分析,可以使用代码等, 提供的品鉴 分析特设的选择。

其他提示

的Getopt ::龙没有做到这一点。您可以自己分析该选项... e.g。

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

或修改的Getopt ::龙来处理它(或修改上面的代码,如果你需要处理更多种选择)。

我有点偏,但是我用的Getopt ::无论过去解析未知参数。

潜在的,你可以使用的"选项的散列值"特征。

例如,我想到允许用户设置的任意的过滤器在分析通过一系列的对象。

GetOptions(my $options = {}, 'foo=s', 'filter=s%')

my $filters = $options->{filter};

然后叫它喜欢

perl ./script.pl --foo bar --filter baz=qux --filter hail=eris

这将建立喜欢的东西..

$options = {
          'filter' => {
                        'hail' => 'eris',
                        'baz' => 'qux'
                      },
          'foo' => 'bar'
        };

当然$过滤器,将有价值相关的"过滤器"

祝你好运!我希望有人发现这很有帮助。

文档

参数回拨

一个特殊的选项“名” <>可以用来指定一个子程序来处理非选项参数。当GetOptions()遇到一个论点看起来不像一个选项,它会立即调用这个子程序,传递给它一个参数:参数名称。

嗯,实际上这是stringifies的参数名称的对象。

例如:

    my $width = 80;
    sub process { ... }
    GetOptions ('width=i' => \$width, '<>' => \&process);

当施加到下面的命令行:

    arg1 --width=72 arg2 --width=60 arg3

这将调用process("arg1")$width是80,而process("arg2")$width 72和process("arg3")$width是60。

此功能需要配置选项置换,见 “配置的Getopt ::龙”

这是推出自己的选项解析器的好时机。我见过的CPAN的模块没有提供这种类型的功能,你可以经常看他们的实现来获得如何处理解析的螺母和螺栓的良好意识。

顺便说一句,这种类型的代码使我讨厌的Getopt变体:

use Getopt::Long;
&GetOptions(
    'name' => \$value
);

在不一致的资本是郁闷,甚至对谁见过和使用的代码,这种风格很长一段时间的人。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top