Question

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

Was it helpful?

Solution

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.

OTHER TIPS

You can set the defaults after GetOptions, like this:

my @compList;
GetOptions('complist:s@' => \@compList) or pod2usage(2);
@compList = qw(abc xyz) unless @compList;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top