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

What am I doing wrong in this code ?
I'm trying to allow the help usage to be printed if either no command line options are used or if the -h is used.
Use Getopt::Long; Getopt::Long::Configure ("bundling"); if (!GetOptions( 'U:s' => \$upd, 'mod' => \$mod, 'res' => \$res, 'h' => \$help )) { usage(); exit(1); } if ($help) { usage(); exit(1); }
It works if I use
prog.pl -h

But not if I just type
prog.pl

I was expecting the help to be printed in this case also ?

Replies are listed 'Best First'.
Re: GetOptions and help
by wazoox (Prior) on Mar 16, 2006 at 12:11 UTC
    It'ds clearly written into Getopt::Long documentation:
    Trouble Shooting GetOptions does not return a false result when an option is not + sup- plied That's why they're called 'options'.

    So if you want to make some option mandatory, you'll have to check it by yourself :

    usage() unless $res;
      None of the options are mandatory and I don't want them to be. Hence the question still remains . Unless you are suggesting that I have to check for each arguments existence e.g.
      usage() unless $res or $mod or $upd
      This seems an untidy way to do it ?

        If none of the options are mandatory, why would you print usage in the second case?

Re: GetOptions and help
by pboin (Deacon) on Mar 16, 2006 at 12:48 UTC

    Try just testing the number of incoming parms, which is in @ARGV..

    if ( @ARGV == 0 || $help ) { usage(); exit(1); }
      I had previously tried doing this but it seems that in my case @ARGV is always -1 regardless of the number of arguments.
      Hence if I do this
      $numargs = $#ARGV +1; if ($numargs == 0) { usage(); exit(1) }
      The usage always kicks in regardless of any options that may have been used

        GetOptions is destructive: it consumes @ARGV as it processes. You would need to test @ARGV before calling GetOptions.

        I would suggest this instead, though: Just determine what the required arguments are, and test them. In your case, it seems like the required arguments are an alternation:

        unless ( $alt1 or $alt2 or ( $alt3 and $alt4 )) { usage(); exit; }