Beefy Boxes and Bandwidth Generously Provided by pair Networks Joe
go ahead... be a heretic
 
PerlMonks  

RFC Getopt::Hash

by radiantmatrix (Parson)
on Aug 09, 2005 at 15:00 UTC ( #482233=perlmeditation: print w/ replies, xml ) Need Help??

I developed this module for personal use, but am considering submitting it as a CPAN module. I would very much like the Monestary's opionion of it.

Thanks to jdporter, I will need to patch my POD to make clear that this has two puproses: not only to get options into a hash (which Getopt::Long already does), but to get options and set defaults in one statement.

DEPRECATED: leriksen pointed out that Getopt::Long does everything I really want it to do, out of the box. The syntax is a little uglier, but the overhead of an additional module (in maintenance and packaging considerations alone) isn't worth the little bit of syntatic sugar. Thanks to the Monestary for comments received.


NAME

Getopt::Hash - wrapper for Getopt::Long to simply get command-line options into a hash.


SYNOPSIS

use Getopt::Hash; my %opt = GetOptions( 'option_name|on:s' => 'default_value', 'element|e!' => 0, 'count|cnt|c=i' => 5, ); if ($opt{'option_name'} eq 'some_value') { ## do work ## }


DESCRIPTION

Getopt::Hash wraps Getopt::Long in order to quickly get command-line options into a local hash in one statement. Compare the SYNOPSIS code above to the equivalent code using Getopt::Long:

use Getopt::Long; my %opt = ( 'option_name' => 'default_value', 'element' => 0, 'count' => 5, ); GetOptions( 'option_name|on:s' => \$opt{'option_name'}, 'element|e!' => \$opt{'element'}, 'count|cnt|c=i' => \$opt{'count'}, ); if ($opt{'option_name'} eq 'some_value') { ## do work ## }

This presents a maintenance headache, as well as taking longer to initially write.


EXPORTS

GetOptions ( %spec_hash )
Returns a hash of command-line options as parsed by Getopt::Long. %spec_hash is of the form:
'getopt_spec_string' => 'default_value'

where 'getopt_spec_string' is an option spec string as expected by the Getopt::Long module.

The hash returned by this subroutine uses the first form of each option as the key, and the option's value (either as passed on the command-line, or the default) as the value. For example:

my %opt = GetOptions( 'option_name|on:s' => 'default_value', 'element|e!' => 0, 'count|cnt|c=i' => 5, );

when called without any command-line options, results in a hash %opt:

'option_name' => 'default_value', 'element' => 0, 'count' => 5,

As with Getopt::Long's GetOptions subroutine, non-option arguments remain in the @ARGV array.


CONFIGURATION

Configure ( @options )
Sets the configuration options that will be passed to Getopt::Long's Configure method during a call to GetOptions.


HISTORY

Version 0.81
Convert GetOptions to use Getopt::Long's internal method of populating options to hashes.
Version 0.80
Initial release on PerlMonks (http://perlmonks.org/)


AUTHOR

Darren Meyer <darren.meyer@gmail.com>


COPYRIGHT AND DISCLAIMER OF WARRANTY

This module is available under the terms of the MIT License:

Copyright (c)2005 Darren Meyer

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ``Software''), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

package Getopt::Hash; use strict; use warnings; use vars '$VERSION'; $VERSION = '0.81'; #===================================================================== +======== # Hash.pm - module to use Getopt::Long to quickly populate an options +hash #--------------------------------------------------------------------- +-------- # Created : (0.80) 2005-08.Aug-05 by Darren Meyer # Modified: #--------------------------------------------------------------------- +-------- # Dependencies: Getopt::Long #===================================================================== +======== require Exporter; use vars '@ISA','@EXPORT','@CONFIG'; @ISA = 'Exporter'; @EXPORT = 'GetOptions'; require Getopt::Long; ### use %hash = GetOptions(%spec); %spec is like 'process=s' => 'defau +lt_val' sub GetOptions { my %spec = @_; my %opt_hash; my $gol = new Getopt::Long::Parser( config=> [@CONFIG] ); $gol->getoptions(\%opt_hash, keys %spec); foreach (keys %spec) { my $key = $_; $key =~ s/[=\:\|\!]+.*//gs; $opt_hash{$key} = $spec{$_} unless defined $opt_hash{$key} } # use Data::Dumper; # print STDERR Dumper(\%opt_hash); return %opt_hash; } ### will do the equivalent of calling Getopt::Long::Configure; sub Configure { @CONFIG = @_; } 1; __END__ =pod =head1 NAME Getopt::Hash - wrapper for C<Getopt::Long> to simply get command-line +options into a hash. =head1 SYNOPSIS use Getopt::Hash; my %opt = GetOptions( 'option_name|on:s' => 'default_value', 'element|e!' => 0, 'count|cnt|c=i' => 5, ); if ($opt{'option_name'} eq 'some_value') { ## do work ## } =head1 DESCRIPTION Getopt::Hash wraps C<Getopt::Long> in order to quickly get command-lin +e options into a local hash in one statement. Compare the L</SYNOPSIS> code abo +ve to the equivalent code using C<Getopt::Long>: use Getopt::Long; my %opt = ( 'option_name' => 'default_value', 'element' => 0, 'count' => 5, ); GetOptions( 'option_name|on:s' => \$opt{'option_name'}, 'element|e!' => \$opt{'element'}, 'count|cnt|c=i' => \$opt{'count'}, ); if ($opt{'option_name'} eq 'some_value') { ## do work ## } This presents a maintenance headache, as well as taking longer to init +ially write. =head1 EXPORTS =over 1 =item C<GetOptions> C<( %spec_hash )> Returns a hash of command-line options as parsed by C<Getopt::Long>. C<%spec_hash> is of the form: 'getopt_spec_string' => 'default_value' where C<'getopt_spec_string'> is an option spec string as expected by +the C<Getopt::Long> module. The hash returned by this subroutine uses the first form of each optio +n as the key, and the option's value (either as passed on the command-line, or +the default) as the value. For example: my %opt = GetOptions( 'option_name|on:s' => 'default_value', 'element|e!' => 0, 'count|cnt|c=i' => 5, ); when called without any command-line options, results in a hash C<%opt +>: 'option_name' => 'default_value', 'element' => 0, 'count' => 5, As with C<Getopt::Long>'s GetOptions subroutine, non-option arguments +remain in the C<@ARGV> array. =back =head1 CONFIGURATION =over 1 =item C<Configure> C<( @options )> Sets the configuration options that will be passed to C<Getopt::Long>' +s Configure method during a call to C<GetOptions>. =back =head1 HISTORY =over 1 =item Version 0.81 Convert C<GetOptions> to use C<Getopt::Long>'s internal method of popu +lating options to hashes. =item Version 0.80 Initial release on PerlMonks (L<http://perlmonks.org/?node=RFC%20Getop +t::Hash>) =back =head1 AUTHOR Darren Meyer <darren.meyer@gmail.com> =head1 COPYRIGHT AND DISCLAIMER OF WARRANTY This module is available under the terms of the MIT License: Copyright (c)2005 Darren Meyer Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the rig +hts to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is furnish +ed to do so, subject to the following conditions: The above copyright notice and this permission notice shall be include +d in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES +S OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILIT +Y, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHAL +L THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISIN +G FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + IN THE SOFTWARE. =cut

Updates:

  • 2005-08.Aug-09 : Change to GetOptions sub thanks to a swift observation by jdporter, add comment to intro regarding upcoming POD patch.
  • 2005-08.Aug-10 : Module deprecated, thanks leriksen!

<-radiant.matrix->
Larry Wall is Yoda: there is no try{} (ok, except in Perl6; way to ruin a joke, Larry! ;P)
The Code that can be seen is not the true Code
"In any sufficiently large group of people, most are idiots" - Kaa's Law

Comment on RFC Getopt::Hash
Select or Download Code
Re: RFC Getopt::Hash
by jdporter (Canon) on Aug 09, 2005 at 15:11 UTC
    You seem to have overlooked the fact that Getopt::Long already supports getting options into a hash. (See the 'Storing options in a hash' section of the Getopt::Long man page.)
    use Getopt::Long; my %opt = ( 'option_name' => 'default_value', 'element' => 0, 'count' => 5, ); GetOptions( \%opt, 'option_name|on:s', 'element|e!', 'count|cnt|c=i', );

      Yes, I missed that. However, that's only half of my purpose, as the other half is to get the options into a hash and set default values in one statement.

      I shall make a note to update my POD to clarify that.

      <-radiant.matrix->
      Larry Wall is Yoda: there is no try{} (ok, except in Perl6; way to ruin a joke, Larry! ;P)
      The Code that can be seen is not the true Code
      "In any sufficiently large group of people, most are idiots" - Kaa's Law
        Next can you make GO::L handle short and long options sanely?
Re: RFC Getopt::Hash
by leriksen (Curate) on Aug 10, 2005 at 02:21 UTC
    Just to add the comment that even if you arent using a hash, you can have default values witrh Getopt::Long - heres a snippet from some code I'm writing right now

    ... use Getopt::Long; use Pod::Usage; ... GetOptions( 'd|dir=s' => \( my $outDir = '.' ), 'f|file=s' => \( my $inFile ), 'l|log=s' => \( my $logFile = './tu_log.conf' ), ); unless ( $inFile ) { pod2usage( -exitval => 1, -output => \*STDERR ); } ... __END__ =pod =head1 NAME Retail_PickList_Generator.pl - generate picklists for outstanding +Retail orders. =head1 SYNOPSIS Retail_PickList_Generator.pl --file <incoming retail order file> [ +--log <log config file> --dir <directory to write picklists to>] =cut

    With the defaults, I only need supply the inward file name. And I get more specialised behaviour by passing in --dir or --log as required...

    ...it is better to be approximately right than precisely wrong. - Warren Buffet

      Hm. Well. Now I'm glad I submitted an RFC here before sending this to CPAN and blithely duplicating perfectly acceptible functionality.

      Thank you for pointing this out.

      <-radiant.matrix->
      Larry Wall is Yoda: there is no try{} (ok, except in Perl6; way to ruin a joke, Larry! ;P)
      The Code that can be seen is not the true Code
      "In any sufficiently large group of people, most are idiots" - Kaa's Law

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlmeditation [id://482233]
Approved by Mutant
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2014-04-17 03:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (439 votes), past polls