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.
In reply to Re: generic getopt to hash
by ELISHEVA
in thread generic getopt to hash
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |