سؤال

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