2

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

MrDuk
  • 16,578
  • 18
  • 74
  • 133

2 Answers2

4

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.

Miller
  • 34,962
  • 4
  • 39
  • 60
  • Thanks - I've made your changes, but now I've noticed something else; only one value is saved in the array: `--complist COMPA COMPB` produces only `COMPA` – MrDuk Apr 04 '14 at 13:34
1

You can set the defaults after GetOptions, like this:

my @compList;
GetOptions('complist:s@' => \@compList) or pod2usage(2);
@compList = qw(abc xyz) unless @compList;
Jim Davis
  • 5,241
  • 1
  • 26
  • 22