我认为这很简单:
my $man = 0;
my $help = 0;
my @compList = ('abc', 'xyz');
my @actionList = ('clean', 'build');
## Parse options and print usage if there is a syntax error,
## or if usage was explicitly requested.
GetOptions('help|?' => \$help, man => \$man, 'complist:s@' => \@compList, 'action:s@' => \@actionList) or pod2usage(2);
然而,当我这样做时:
script.pl --action clean
我打印我的actionList
,它只是将我的参数追加到最后:clean build clean
答案 0 :(得分:3)
对于标量,在GetOptions调用中设置默认值。但是,对于数组,您需要更明确地使用逻辑。
## Parse options and print usage if there is a syntax error,
## or if usage was explicitly requested.
GetOptions(
'help|?' => \(my $help = 0),
'man' => \(my $man = 0),
'complist:s@' => \my @compList,
'action:s@' => \my @actionList,
) or pod2usage(2);
# Defaults for array
@compList = qw(abc xyz) if !@compList;
@actionList = qw(clean build) if !@actionList;
注意,因为$help
和$man
只是布尔标志,所以实际上不需要初始化它们。依赖于默认值undef
可以正常工作,除非您尝试在某处打印它们的值。
答案 1 :(得分:1)
您可以在GetOptions
之后设置默认值,如下所示:
my @compList;
GetOptions('complist:s@' => \@compList) or pod2usage(2);
@compList = qw(abc xyz) unless @compList;