in reply to generic getopt to hash

The recent versions of Getopt::Long support a really wide variety of option syntax, including all of the examples you gave above (except that you would need to use '-v' instead of 'v': it does need a character to distinguish options from option values). You can also use both long and short options, include or omit equal signs, follow each option with a single value or many, and even do some lightweight type checking. Order doesn't matter - you can have a multi-valued option before or after other options. Command lines such as:

can be parsed with the following code:

use strict; use warnings; use Getopt::Long; use Data::Dumper; #------------------------------------------------------- sub parseArgs { my ($aRules, $aArgs) = @_; # version used with 5.8.8 expects arguments in @ARGV # the version in the 5.10 core has a function that can # read arguments from any array, not just @ARGV. local @ARGV = @$aArgs; Getopt::Long::GetOptions(my $hOpts={}, @$aRules); return $hOpts; } #------------------------------------------------------- my $aRules = [ 'name=s' #allow any string as value , 'val|v=i' #allow --val or -v, require number , 'list=s@{,}' #allow arbitrary lists of values ]; my $hParsed = parseArgs($aRules, \@ARGV); print Dumper($hParsed);

For all of these various combinations of command line arguments it would produce the same data structure:

$VAR1 = { 'name' => 'joe', 'val' => 0, 'list' => [ 'a', 'b', 'c' ] };

Best, beth

Update: added example with multivalued option followed by other options, as per request of jakobi.

Replies are listed 'Best First'.
Re^2: generic getopt to hash
by jakobi (Pilgrim) on Oct 04, 2009 at 13:42 UTC

    It made be curious enough to ask the author himself for clarification wrt code vs docs. Here's part of Johans reply to me:

    > /me
    > According to my reading of the 2.38 docs however, the --list option
    > should have eaten -v as well, as it states that args can start with
    > - or --. Which I'd take to mean that all further elements in @ARGV
    > are eaten by --list.
    
    /johan
    Args can start with -/-- only if mandatory. list=s@{,} allows for
    many arguments, but does not require them. list=s@{,4} would *require*
    4 arguments and eat -/-- args if necessary.
    

    He also pointed me to !FINISH to help with stopping option parsing early. Together with ::Long's option aliasing, this should suffice to replace some of my looping thru @ARGV to massage arguments before getopt :).

    Thanx to Johan & Beth for her excellent example above!