kesterkester has asked for the wisdom of the Perl Monks concerning the following question:

Greetings Knowledgeable Monks,

I recently shot myself in the foot with Getopt::Long by setting up a hash of default parameters, and then misspelling one of the parameter names in the GetOptions call, like this:

# set up default values for parameters: my %pars = ( item => 'default value', ); GetOptions ( \%pars, 'items=s', # NOTE MISPELLING-- "items" s/b "item" ) or die "bad GetOptions $!"; # use $pars{item}, which is unaffected by an --items argument
That is, my typo autovivifies a new entry in the parameter hash, which is then never used. It took a painful amount of time to figure out why the arguments weren't responding correctly!

Does anyone have a clever way of checking for mistakes (typos) of this type? The best I can do is something like this:

my @opts = ( { name => 'item1', type => '=s', dval => 'default_value1' }, { name => 'item2', type => '=s', dval => 'default_value2' }, ); my %pars = map { $opts[$_]{name} , $opts[$_]{dval} } 0..$#opts; my @args = map { $opts[$_]{name} . $opts[$_]{type} } 0..$#opts; GetOptions ( \%pars, @args ) or die "bad GetOptions $!";
but I'd love to see something else that could protect me from my typos, if someone has something better.

Replies are listed 'Best First'.
Re: Getopt::Long Gotcha, request advice
by Abigail-II (Bishop) on Nov 21, 2003 at 16:50 UTC
    If I want to use default value with Getopt::Long, I do:
    GetOptions ( 'item=s' => \my $item = 'default', );
    If you want to work with a hash like you do, you can do:
    my %pars = ( my $item = item => 'default value', ); GetOptions ( \%pars, "$item=s", );

    Abigail

Re: Getopt::Long Gotcha, request advice
by Anonymous Monk on Nov 21, 2003 at 16:52 UTC
    use Hash::Util qw/lock_keys/;; my %pars = ( item => 'default', ); lock_keys(%pars);

    And now, at least, you'll get an exception when you try to pass 'items' or any uniq abbreviation (like 'item') on the c-line, or if you mispell the key anywhere else!

Re: Getopt::Long Gotcha, request advice
by Zed_Lopez (Chaplain) on Nov 21, 2003 at 16:44 UTC
Re: Getopt::Long Gotcha, request advice
by bschmer (Friar) on Nov 21, 2003 at 16:30 UTC
    I've done a similar thing on occasion and I agree that it's kind of a pain in the butt to put into every piece of code that I write. Perhaps it's time that Getopts::Long got a little facelift or a frontend.

    Of course, the operation of Getopt::Long is quite resonable as is, but that's not much help when you make a typo.

Re: Getopt::Long Gotcha, request advice
by graff (Chancellor) on Nov 22, 2003 at 16:08 UTC
    Your question reminded me of a nifty trick I learned here at the Monastery, thanks to grinder, who posted his idea a few months ago on another SoPW question: Re: Referencing built-ins.

    The approach there involves just a tad more overhead in setting up the options, but if you use getopts a lot, I think it could be a useful habit to get into.