문제

I thought it was as easy as:

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);

However, when I do:

script.pl --action clean

And I print my actionList, it just appends my parameter to the end: clean build clean

도움이 되었습니까?

해결책

For scalars set the default in the call to GetOptions. However, for arrays, you'll need to be more explicit with your logic.

## 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;

Note, because $help and $man are just boolean flags, it's not actually necessary to initialize them. Relying on their default of undef works fine unless you're trying to print their values out somewhere.

다른 팁

You can set the defaults after GetOptions, like this:

my @compList;
GetOptions('complist:s@' => \@compList) or pod2usage(2);
@compList = qw(abc xyz) unless @compList;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top