Perl的Getopt :: Long解析参数我没有提前定义吗?

时间:2009-02-09 20:48:33

标签: perl getopt-long

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

连连呢?提前谢谢。

6 个答案:

答案 0 :(得分: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.

解析常规选项后,您可以使用provided by runrig之类的代码来解析临时选项。

答案 1 :(得分:5)

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

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

或者修改Getopt :: Long来处理它(或修改上面的代码以便在需要时处理更多种类的选项)。

答案 2 :(得分:2)

我有点偏爱,但我过去使用了Getopt :: Whatever来解析未知的论点。

答案 3 :(得分:1)

可能您可以使用“Options with hash values”功能。

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

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

当然$过滤器的值与'filter'

相关联 祝你好运!我希望有人发现这有用。

答案 4 :(得分:0)

来自documentation

Argument Callback

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

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

例如:

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

应用于以下命令行时:

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

这会在process("arg1")为80时$widthprocess("arg2")$width时为process("arg3"),而$width为60时为{{1}}。

此功能需要配置选项置换,请参阅部分 "Configuring Getopt::Long"

答案 5 :(得分:-1)

现在是滚动自己的选项解析器的好时机。我在CPAN上看到的所有模块都没有提供这种类型的功能,你可以随时查看它们的实现,以便更好地理解如何处理解析的细节。

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

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

即使对于长时间看过和使用过这种代码的人来说,不一致的大写也是令人抓狂的。