gpt4 book ai didi

perl - 如何设置GetOpt的默认值?

转载 作者:行者123 更新时间:2023-12-03 09:25:03 26 4
gpt4 key购买 nike

我认为这很简单:

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

最佳答案

对于标量,在 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 只是 bool 标志,因此实际上没有必要初始化它们。除非您尝试在某处打印它们的值,否则依赖它们的默认 undef 效果很好。

关于perl - 如何设置GetOpt的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22849410/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com