getopt::long 如何与混合多头/空头期权配合使用?

  • 本文关键字:混合 getopt long perl
  • 更新时间 :
  • 英文 :


Getopt的描述说,同一个选项都接受'-'和'--',并且短选项可以捆绑在一起。假设"帮助"是一种选择,那么:

script --help     # succeeds
script --h        # succeeds
script -h         # fails

如果我们有两个或多个具有唯一第一个字符的选项("ab","cd"(,则-ac不起作用,但--a和--c可以。我已经查看了所有getopt选项,我认为正确使用了它们。我是否错过了一个选项,或者我误解了getopt的描述?

实际代码为:

Getopt::Long::Configure ( "gnu_getopt"
, "auto_abbrev"
, "bundling"
, "ignore_case_always"
);
GetOptions ( 'normalize'   => $normalize
, 'exclude=s'   => @exclude
, 'help'        => $help
, 'include=s'   => @include
, 'recurse'     => $recurse
, 'update'      => $update
, '2update'     => $update2
, 'copy'        => $copy
, 'move'        => $move
, 'n'           => $normalize
, 'e=s'         => @exclude
, 'h'           => $help
, 'i=s'         => @include
, 'r'           => $recurse
, 'u'           => $update
, '2'           => $update2
, 'c'           => $copy
, 'm'           => $move
);

使用重复的getopts参数允许识别"-h"和"--h"。使用重复的选项,事情似乎按预期工作,但我对getopt描述的阅读似乎说重复的代码是不必要的。

对于bundling--必须用于长选项。-只能用于您未定义任何的空头期权。

您可以禁用捆绑(nobundlinggnu_getopt后,而不是gnu_getopt已经启用的bundling(。

use Getopt::Long qw( );
for (
[qw( --help )],
[qw( --h )],
[qw( -h )],
) {
@ARGV = @$_;
say "@ARGV";
Getopt::Long::Configure(qw( gnu_getopt nobundling auto_abbrev ignore_case_always ));
Getopt::Long::GetOptions(
'normalize' => my $normalize,
'exclude=s' => my @exclude,
'help'      => my $help,
'include=s' => my @include,
'recurse'   => my $recurse,
'update'    => my $update,
'2update'   => my $update2,
'copy'      => my $copy,
'move'      => my $move,
);
say $help // "[undef]";
}

或者您可以使用help|h一次性定义多头(--(和空头(-(选项。

use Getopt::Long qw( );
for (
[qw( --help )],
[qw( --h )],
[qw( -h )],
) {
@ARGV = @$_;
say "@ARGV";
Getopt::Long::Configure(qw( gnu_getopt auto_abbrev ignore_case_always ));
Getopt::Long::GetOptions(
'normalize|n' => my $normalize,
'exclude|e=s' => my @exclude,
'help|h'      => my $help,
'include|i=s' => my @include,
'recurse|r'   => my $recurse,
'update|u'    => my $update,
'2update|2'   => my $update2,
'copy|c'      => my $copy,
'move|m'      => my $move,
);
say $help // "[undef]";
}

两个程序都输出以下内容:

--help
1
--h
1
-h
1
GetOptions(
'path|p=s'  => $opt{path},
'help|h'    => $opt{help},
'man|m'     => $opt{man},
'debug|d'   => $opt{debug}
) or pod2usage(2);

最新更新