4

我知道如何使用 Perl 的 Getopt::Long,但我不确定如何将其配置为接受任何尚未明确定义的“--key=value”对并将其粘贴在哈希中。换句话说,我不提前知道用户可能想要什么选项,所以我无法定义所有选项,但我希望能够解析所有选项。

建议?提前谢谢。

4

6 回答 6

12

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.

解析常规选项后,您可以使用诸如runrig 提供的代码来解析临时选项。

于 2009-02-09T21:28:02.397 回答
5

Getopt::Long 不会那样做。您可以自己解析选项...例如

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

或者修改 Getopt::Long 来处理它(或者修改上面的代码来处理更多种类的选项,如果你需要的话)。

于 2009-02-09T20:57:00.880 回答
2

我有点偏心,但我过去曾使用 Getopt::Whatever 来解析未知参数。

于 2009-02-10T18:41:31.407 回答
1

潜在地,您可以使用“带有哈希值的选项”功能。

例如,我希望允许用户在解析对象数组时设置任意过滤器。

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'
        };

当然 $filters 将具有与 'filter' 关联的值

祝你好运!我希望有人觉得这很有帮助。

于 2010-05-26T20:45:19.200 回答
0

文档中:

参数回调

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

好吧,实际上它是一个字符串化参数名称的对象。

例如:

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

当应用于以下命令行时:

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

这将调用process("arg1")while$width为 80、process("arg2")while$width为 72 和process("arg3")while$width为 60。

此功能需要配置选项 permute,请参阅 “配置 Getopt::Long”部分。

于 2009-07-21T19:53:13.607 回答
-1

这是推出您自己的选项解析器的好时机。我在 CPAN 上看到的所有模块都没有提供这种类型的功能,您始终可以查看它们的实现以很好地了解如何处理解析的具体细节。

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

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

不一致的大小写是令人抓狂的,即使对于长期看过和使用这种代码风格的人来说也是如此。

于 2009-02-10T08:12:43.610 回答