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

Given the following:
use vars qw /%option/; getopt('m:f:l:s:q:h', \%option);
how do you test for "no command line options specified" if each key in %option equals 1 by default?

Another related question: I'm trying to say "if you use this option, it needs to accompany another option", and I just realized that what I'm doing doesn't work as expected. Here's what I have:

if ($option{f}) { die "You must use the -f option along with another option\nRun $0 -h + to view all available options\n" unless (($option{f}) && ($option{l} || $option{m} || $option{d}) +); $ctlFile = "$option{f}"; }
TIA,
--s

Replies are listed 'Best First'.
Re: Boundary conditions with Getopt::Std
by Abigail-II (Bishop) on Jan 30, 2004 at 16:28 UTC
    If no command line options where specified, %option will be empty. The value of 1 is set if the option is present, but the option doesn't have an argument. (At least, that's what the documentation says, some trivial testing suggests that if no argument is given, undef will be used).

    As for your second question, I'd use exist to check whether an option is set, or else you might get tripped by the fact that the option is used, but the argument is false.

    Abigail

Re: Boundary conditions with Getopt::Std
by Limbic~Region (Chancellor) on Jan 30, 2004 at 16:25 UTC
    blink,
    I know it can be confusing, but I think you want getopts from Getopt::Std instead. Here is a fully functional template for you.
    #!/usr/bin/perl -w use strict; use Getopt::Std; my %Opt; Get_Args(); sub Get_Args { my $Usage = qq{Usage: $0 [options] -h : This help message. -a : BOGUS - requires argument if used -A : BOGUS -b : BOGUS } . "\n"; getopts( 'ha:Ab' , \%Opt ) or die $Usage; die $Usage if $Opt{h}; die "You did not enter any options\n" if ! %Opt; if ( exists $opt{a} || exists $opt{A} ) { if ( ! ( exists $opt{a} && exists $opt{A} ) ) { die "You must use -a and -A together\n"; } } }
    Cheers - L~R
Re: Boundary conditions with Getopt::Std
by duff (Parson) on Jan 30, 2004 at 16:27 UTC
    how do you test for "no command line options specified" if each key in %option equals 1 by default?

    They only equal 1 if the option is specified. For those options that take a value, you either get 1 or the value specified on the command line.

    Another related question: I'm trying to say "if you use this option, it needs to accompany another option",
    unless ($option{f} && $option{h}) { die "If you use -f, you must also use -h, and vice versa."; }

    Assuming I understand you correctly. Or if you wanted the relation to be one-way (i.e., -f needs to accompany -h, but -h doesn't need to accompany -f) then you could do something like this:

    if ($option{f} && !$option{h}) { die "If you use -f, you must also use -h"; } if ($option{h}) { ... }