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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.