in reply to problem with Getopt::Long

Hi syedtoah

There are a couple of probs with the given code

here is a fixed version that should work as expected.
#!/use/your/bin/perl -w use strict; unless (@ARGV) {&usage} use Getopt::Long; my %options; my $ret = GetOptions( "i" => \$options{i}, "o=s" => \$options{o}, "p=s" => \$options{p}, "h" => \$options{h} ); if ($ret eq "" || $options{'h'}) {&usage} if ($options{i}) { print "i is enabled\n"; } if ($options{o}) { print "o is enabled file is $options{o}\n"; } if ($options{p}) { print "p is enabled value is $options{p}\n"; } sub usage { print " \nCommand line options: -i interactive -o file give a file -h help -p value personal\n"; exit; }

Update
As Nkuvu points out Getopts only eats up the valid options from @ARGV, anything else will remain so the test for @ARGV will pass if there are any non-option values in the command line.

Replies are listed 'Best First'.
Re^2: problem with Getopt::Long
by Nkuvu (Priest) on Aug 20, 2004 at 10:07 UTC
    Getopt eats up the values in @ARGV so it is alway empty

    Just to be nitpicky -- not quite. Getopt eats the options in @ARGV. Anything else will remain. Consider the following:

    #!/usr/bin/perl use Getopt::Long; GetOptions( "i" => \$options{i}, "o=s" => \$options{o}, "p=s" => \$options{p}, "h" => \$options{h} ); foreach $arg (@ARGV) { print "$arg is still in ARGV\n"; } foreach $opt (keys %options) { print "$opt is $options{$opt}\n" if $options{$opt}; }
    and note the output:
    nkuvu$ perl try.pl --i h --o=foo h is still in ARGV o is foo i is 1

    I have used this to check some command line inputs. Specifically, for most of my scripts anything specified on the command line should be an option. Anything after that is an error. So I'd use it sort of like:

    GetOptions( #whatever ); die "Gah! (with appropriate error message here)\n" if (@ARGV);
      You are of course correct, I was trying to keep my posting brief and typed the short version of what was in my head. Then using a set of test cases whith only valid command line switches never made me think about it again.

      Cheers,
      R.

        Another thing to note is that a double dash will stop option processing, so if I enter
        perl try.pl --i -- h --o=foo
        to the script the (valid) o option won't be parsed either and will remain in ARGV.

        The only reason I bring it up now is that I find it amusing that in a nitpicky post, I didn't specify all cases.