perl_mystery has asked for the wisdom of the Perl Monks concerning the following question:

I have a script which I run using the following command line,what I noticed is people forget to add the options(-b,-l) and ran them without it.

finddata.exe -b file.txt -l data.txt

finddata.exe -b file.txt

finddata.exe -l data.txt

I tried use the below but it fails when the tool is run as below finddata.exe -b file.txt data.txt (note the missing -l before data. +txt). if ($#ARGV < 1) { print "USAGE"; }

Basically I want to make sure the optionsa re added.How do I that?

Replies are listed 'Best First'.
Re: How to make sure to print usage when the options are not entered?
by GrandFather (Saint) on Jan 27, 2011 at 01:13 UTC

    Use Getopt::Std to parse the options for you then check that you got everything:

    use strict; use warnings; use Getopt::Std; my %opts; getopts('b:l:', \%opts); if (! exists $opts{b} || ! exists $opts{l}) { die "Both -b and -l options are required\n"; } print "-b: $opts{b}, -l $opts{l}\n";
    True laziness is hard work
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: How to make sure to print usage when the options are not entered?
by toolic (Bishop) on Jan 27, 2011 at 01:14 UTC
    Getopt::Long
    use strict; use warnings; use Getopt::Long; my $lfile; my $bfile; GetOptions ( 'l=s' => \$lfile, 'b=s' => \$bfile ) or die; die "Unexpected args: @ARGV" if @ARGV; die "Must specify -l or -b" unless $lfile or $bfile;
    Pod::Usage is handy too.
Re: How to make sure to print usage when the options are not entered?
by jethro (Monsignor) on Jan 27, 2011 at 01:23 UTC

    You have 3 arguments, so $#ARGV is 2, your if is false and nothing gets printed

    But that's beside the point, you really should use either Getopt::Std or Getopt::Long, two modules that take care of command line arguments for you. Maybe you haven't used a module yet, this is the perfect time to use your first one. It's easy and both modules are already included in any normal perl distribution, so you should have them ready for use

    Getopt::Std is the simpler module, but you have to check for yourself that at least one of the options was specified, Getopt::Long is more complex, but there you can specify whether options are optional or required.

Re: How to make sure to print usage when the options are not entered?
by Anonymous Monk on Jan 27, 2011 at 07:59 UTC
    We've been through this before, hire a programmer.