You can pass code references to GetOptions, such as

perl -we 'use Getopt::Long; my @channels; GetOptions("channel=s", sub +{ push @channels, {"channel", $_[1]}; }, "forever", sub { $channels[- +1]{"forever"} = 1; }, "minutes=n", sub { $channels[-1]{"minutes"} = $ +_[1]; }, "hours=n", sub { $channels[-1]{"hours"} = $_[1]; }, ); use D +ata::Dumper; print Dumper [@channels];' -- -channel 1 -forever -chann +el 2 -minutes 10 -hours 20 -channel 3 -forever
which gives
$VAR1 = [ { 'forever' => 1, 'channel' => '1' }, { 'hours' => 20, 'minutes' => 10, 'channel' => '2' }, { 'forever' => 1, 'channel' => '3' } ];

Of course, you may want a different data structure, use whatever is convenient for the rest of your code.

Update: POSIX getopt (and its extension, GNU's getopt_long) has the correct interface: the right way to get options is to call code provided by the developper. The way perl's Getopt and Getopt::Long tries to be smart and store the data in structures automatically is wrong. It sometimes works, but more often it doesn't, just like this example shows it. It's not too difficult for the developper to write simple callbacks sub { $fooswitch = 1 } instead of a reference \$fooswitch, and it offers much more flexibility.


In reply to Re: GetOptions problem by ambrus
in thread GetOptions problem by bory

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.