ikegami and Tanktalus have already shown you examples of better ways to do it, but in the spirit of TIMTOWTDI here are a couple other (ab)uses of the Getopt::Long features. The first takes advantage of the ability to assign a user-defined subroutine to an option to use during processing (which I use to set a flag and then store the value of the option). The second creates a copy of the original command line before it is processed and simply uses a regex to determine if a given option was present (without attempting to retrieve the value). I used a combination of single- and double-dashes to show it works both ways.

use strict; use warnings; use Getopt::Long; # make a copy of the cmd line before GetOptions processes it my $cmd_line = join( ' ', @ARGV ); my $saw_something = 0; my @things; GetOptions( 'something:s' => sub { shift @_; $saw_something = 1; push( @things, grep { $_ ne '' } @_ + ); } ); if( $cmd_line =~ m/-?-something\b/ ) { print "I saw something on the cmd line\n"; } if( $saw_something ) { if( scalar @things ) { print 'And it was ' . join( ' ', @things ) . "\n"; } else { print "But I don't know what I saw\n"; } }

For example:

C:\>test.pl --something NodeReaper I saw something on the cmd line And it was NodeReaper
There are times, however, when we know we saw something but we don't want to know what it was:
C:\>test.pl --something I saw something on the cmd line But I don't know what I saw
This works for multiple values, too:
C:\>test.pl --something a -something grue I saw something on the cmd line And it was a grue


In reply to Re: using Getopt::Long, arguments and no arguments possible? by bobf
in thread using Getopt::Long, arguments and no arguments possible? by dark314

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.