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

Dear Monks,

I need to give the command line options to a module. I retrieve them like
$getoptret = $p->getoptions( 'house' =>\$house, 'dog|d:s' =>\$dog, .... .... } ;
How do I get all this information in a hash. At the moment I do:
 %my_hash = { house => $house, dog => $dog, ..... } ;
One of the problems I have with this approach is that when I add a new options, I have to modify my program at two places!

Any suggestions ?
Thanks in advance
Luca

2005-11-08 Retitled by g0n, as per Monastery guidelines
Original title: 'Getopt::Long'

Replies are listed 'Best First'.
Re: Getting Getopt::Long values into a hash
by borisz (Canon) on Nov 08, 2005 at 12:55 UTC
    my %h; GetOptions( \%h, 'house=s', 'dog=s', );
    Boris
Re: Getting Getopt::Long values into a hash
by virtualsue (Vicar) on Nov 08, 2005 at 12:57 UTC
Re: Getting Getopt::Long values into a hash
by duelafn (Parson) on Nov 08, 2005 at 13:01 UTC

    Are you looking for this?

    $getoptret = $p->getoptions( \%my_hash, 'house', 'dog|d:s' );

    If you want more control over where things are stored you could also do something like:

    $getoptret = $p->getoptions( 'house' => \$my_hash{house}, 'dog|d:s' => \$my_hash{mutt}, );

    Edit: D'oh, too slow

    Good Day,
        Dean

      It only seems to work when I use it like:
      $getoptret = $p->getoptions( 'house' => \$my_hash->{house}, 'dog|d:s' => \$my_hash->{mutt}, );
      what is exactly the difference between $my_hash->{something} and $my_hash{something} ?

      Thanks a lot!
      Luca

        It seems that you must have $my_hash as a hashref, rather than having a %my_hash. The arrow-form adds a dereference to the LHS value. In my example, #1 and #2 are equivalent:

        my $ref = { foo => "bar" }; print ${$ref}{"foo"}; #1 prints "bar" print $ref->{"foo"}; #2 prints "bar" print $ref{"foo"}; #3 prints "" # and under strictures throws a: # "Global symbol "%ref" requires explicit package name"

        $ref{"foo"} only returns a value if there is a hash named %ref.

Re: Getting Getopt::Long values into a hash
by Aristotle (Chancellor) on Nov 08, 2005 at 22:31 UTC

    Note though that when you refer to $my_hash->{huose} later in your code, you will not be alerted about the typo, rather your code will fail silently but keep running. If this typo was in a variable name, such as $opt_huose, you’d get a loud complaint from strict about using an undeclared variable.

    So I advise against putting options in a hash. Instead, I recommend demerphq’s proposed GetOpt::Long usage style – which is how I write my commandline utilities now.

    Makeshifts last the longest.