My question is quite simple, but unfortunately I can't resolve it:

I'd like to use a command line option with- or without an argument as a flag:

if it has an argument then the value of my scalar should be the argument, otherwise its value should be the default value. The command line may contain other arguments and I'd like to keep the @ARGV untouched.

I've started to play with the Getopt::Long modul and felt myself very close to the solution, but unfortunately it wasn't perfect:

use Getopt::Long; #my $foo = 1; GetOptions ('foo=s', \$foo); print "foo: $foo\n" if $foo; print "Unprocessed by Getopt::Long\n" if $ARGV[0]; foreach (@ARGV) { print "$_\n"; }

eg.:
>perl test.pl something -foo "my argument"
works fine, but
>perl test.pl something -foo
results a message: "Option foo requires an argument", even if you added a default value for your option in the code (see the commented line). (The GetOptions ('foo:s', \$foo) with the : type) doesn't drop error message, but the $foo has no value at all.) What I wanna reach is $foo with the default value (without error message) or $foo with the value if there is a value for -foo. Of course I no need the default value if there isn't the -foo argument in the command line at all.

I found a quite similar problem in between the recent nodes: Requiring option values in Getopt::Long, but there is no solution for my problem...

Thanks in advance


In reply to command line option with- or without argument by Vasek

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.