2014-04-03 49 views
0

我认为它是那么容易,因为:如何设置GetOpt的默认值?

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:[email protected]' => \@compList, 'action:[email protected]' => \@actionList) or pod2usage(2); 

然而,当我这样做:

script.pl --action clean 

而且打印我actionList,它只是追加我的参数来结尾:clean build clean

回答

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:[email protected]' => \my @compList, 
    'action:[email protected]' => \my @actionList, 
) or pod2usage(2); 

# Defaults for array 
@compList = qw(abc xyz) if [email protected]; 
@actionList = qw(clean build) if [email protected]; 

注意,因为$help$man只是布尔标志,它实际上不是必要的初始化。依靠它们的默认值undef可以正常工作,除非您尝试在某处打印其值。

+0

谢谢 - 我已进行了更改,但现在我发现别的东西;只有一个值被保存在数组中:'--complist COMPA COMPB'只产生'COMPA' – MrDuk

+0

Nevermind - 使用'{x,y}'结果是这里的解决方案。 – MrDuk

1

可以GetOptions后的默认设置,如下所示:

my @compList; 
GetOptions('complist:[email protected]' => \@compList) or pod2usage(2); 
@compList = qw(abc xyz) unless @compList;