Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

using "Getopt::Long" how to check parameter mandatory

by shan_emails (Beadle)
on Aug 24, 2010 at 14:07 UTC ( #856941=perlquestion: print w/replies, xml ) Need Help??
shan_emails has asked for the wisdom of the Perl Monks concerning the following question:

Hi All,

I used Getopt::Long module for command line Input Arguments. The perl file is executed without parameters. But i want the perl file won't execute without parameters. How can i control this case using Getopt::Long.


use Getopt::Long; my $data = "file1"; my $length = 4; my $verbose; GetOptions ("length=i" => \$length, "file=s" => \$data,"verbose" => + \$verbose);

Here filename is -

when i run in command prompt as below it doesn't show any error.


Thanks in advance,
Shanmugam A.

Replies are listed 'Best First'.
Re: using "Getopt::Long" how to check parameter mandatory
by VinsWorldcom (Parson) on Aug 24, 2010 at 14:45 UTC

    Just check @ARGV after you parse your options:

    use Getopt::Long; my $data = "file1"; my $length = 4; my $verbose; GetOptions ( "length=i" => \$length, "file=s" => \$data, "verbose" => \$verbose ); if (!@ARGV) { print "$0: Argument required.\n"; exit 1 }

    I also like to use POD to document my code; thus, pod2usage can be invoked to produce 'nicer' usage output:

    use Pod::Usage; ... GetOptions( ... ) or pod2usage(-verbose => 0); ... # Make sure at least one argument provided if (!@ARGV) { pod2usage(-verbose => 0, -message => "$0: argument required\n") }
Re: using "Getopt::Long" how to check parameter mandatory
by JavaFan (Canon) on Aug 24, 2010 at 14:46 UTC
    How can i control this case using Getopt::Long.
    As Johan Vromans (author of Getopt::Long) tends to say "mandatory arguments aren't options". Hence, there's no build-in functionality in Getopt::Long to enforce mandatory parameters.

    But you can also die afterwards if certain parameters aren't defined.

      That's a very narrow view of 'command line options'. It is better I believe to think of them as named parameters, some of which may be required and some optional.


      "If God had meant for us to think for ourselves he would have given us brains. Oh, wait..."

        Considering he's the author of the module, he may have an as narrow minded view as he wishes. He made his work available for others to use, if you don't like the module, you have the freedom to write your own, and then you can treat options to not be optional.
Re: using "Getopt::Long" how to check parameter mandatory
by TomDLux (Vicar) on Aug 24, 2010 at 15:23 UTC

    I'm a Getopt::Long fan. Rather than using separate variables, I use the option to put all the arguments into a hash. As well, I integrate with documentation using Pod::Usage. Initializing the options hash provides default values. '-help' displays a brief summary, while '-man' displays the full POD.

    my %options = ( date => prev_day( strftime( '%Y%m%d', localtime + )), qadir => $QADIR, proddir => $PRODDIR, ); GetOptions( \%options, 'date=s', 'qadir=s', 'proddir=s', 'exch=s', 'altexch=s', 'man', 'help', 'alert!', 'debug+' ) || pod2usage(2); pod2usage(1) if $options{'help'}; pod2usage( '-verbose' => 2 ) if $options{'man'};

    To handle mandatory arguments, obviously there's no default. Instead, I test for a value. If '-file' has not been provided, I print the message followed by '-help' summary, and exit with status '1'. The only pain is testing all the requirements and inter-correlations between arguments and coming up with the correct set of error messages. It's very irritating to get an error message for a program, provide the requested argument, and get a next error message.

    pod2usage( { -message => q{Mandatory argument '-file' is missing} +, -exitval => 1 , -verbose => 1 } ) unless $options{file};

    As Occam said: Entia non sunt multiplicanda praeter necessitatem.

Re: using "Getopt::Long" how to check parameter mandatory
by suhailck (Friar) on Aug 24, 2010 at 14:44 UTC
    You can use, die unless @ARGV;
Re: using "Getopt::Long" how to check parameter mandatory
by repellent (Priest) on Aug 25, 2010 at 04:28 UTC
    use Getopt::Long qw(GetOptions); Getopt::Long::Configure(qw(posix_default no_ignore_case)); GetOptions(\my %OPT, "mandatory!", ); die "Option --mandatory not specified.\n" unless exists $OPT{mandatory}; print "OK.\n";

    On the command line:
    $ Option --mandatory not specified. $ --manda Unknown option: manda Option --mandatory not specified. $ --mandatorY Unknown option: mandatorY Option --mandatory not specified. $ --mandatory OK. $ --nomandatory OK.
Re: using "Getopt::Long" how to check parameter mandatory
by Argel (Prior) on Aug 25, 2010 at 01:13 UTC
    You should be doing error checking on whatever the user sends you, right? So if they don't pass something in you can bail while doing those checks. You should also consider if there are some sane default values you could use to reduce the number that are mandatory.

    Elda Taluta; Sarks Sark; Ark Arks

Re: using "Getopt::Long" how to check parameter mandatory
by dasgar (Curate) on Aug 24, 2010 at 18:11 UTC

    What I typically do is take all of the variables that are used in the GetOptions function and initialize them first to a value. For optional parameters, I give their corresponding variables a valid default. For the required parameters, I set their variables to something that I consider to be invalid.

    Then after calling GetOptions, I do a verification on the variables. Basically if any of the variables now have anything that I consider invalid, I call die and provide an error message. In fact, I usually put the GetOptions and validation in a subroutine and do the initialization outside of that subroutine.

    Might not be the best method, but that's how I've handled the issue.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://856941]
Approved by Corion
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (8)
As of 2017-05-29 16:42 GMT
Find Nodes?
    Voting Booth?