in reply to Getopts and required args

Use Getopt::Long.

Breifly, here's an example of what your code may end up looking like:
use strict; use warnings; use Getopt::Long; use vars qw($opt_u $opt_h $opt_a $opt_l); &GetOptions('l=s','u','h','a') || exit 1; print "Option found: u\n" if ($opt_u); print "Option found: h\n" if ($opt_h); print "Option found: a\n" if ($opt_a); if ($opt_l) { print "Option found: l\n"; print " with value: $opt_l\n"; } else { print "You must specify -l\n"; exit 1; }
Note that 'l=s' means that l must be specified with a value, otherwise, GetOptions() fails.

Hope that helps,
Shendal

Replies are listed 'Best First'.
RE: Re: Getopts and required args
by husker (Chaplain) on Jun 22, 2000 at 20:34 UTC
    In this example, it appears that -l is a required switch, which it isn't. Or am I reading this wrong?
    if ($opt_l) { print "Option found: l\n"; print " with value: $opt_l\n"; } else { print "You must specify -l\n"; exit 1; }
    In other words, not having $opt_l should NOT be an error... only a NULL $opt_l. And in perl, is there a difference?
      Well, in my example it is required. I must have misunderstood your question. If you want to require -l to be paired with a value, but not specifying -l is okay, too, try this:

      use strict; use warnings; use Getopt::Long; use vars qw($opt_u $opt_h $opt_a $opt_l); #Note that l=s says that l requires an option # l:s means that it is optional # I have chosen the option method here so that # I can handle it how I want programatically &GetOptions('l:s','u','h','a') || exit 1; print "Option found: u\n" if ($opt_u); print "Option found: h\n" if ($opt_h); print "Option found: a\n" if ($opt_a); if (defined $opt_l) { print "Option found: l\n"; if ($opt_l) { print " with value: $opt_l\n"; } else { print " No value specified.\n"; } }