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

Hi, i have this piece of code
Getopt::Long::GetOptions ( 'u=s' => \$user, 'p=s' => \$passwd, 's=s' => sub { local *_ = \$_[1]; /^([^:]+):(\d+)$/ or die("Invalid format for option s.\n"); $host = $1; $port = $2;}, 'h=s' => \error_detect("h"), ) or error_detect("3 Invalid commmand line options.");
now the problem with this code is that no matter i type -h on the command prompt or not the routine error_detect is still called
i have tried to check all the documentation of getopt::long on cpan but there is nothing of the sort which tells me how to make a switch optional in Getopt::long.
like in GetOpt::STD we can make a switch optional by just typing a semi colon which makes that particular switch optional.
also i would like to know how do i ignore all the rest of the switches if -h is typed.
so basically i want to know two things
how do i make -h an optional switch in Getopt::long( just like we have a semi colon in STD)
if -h is typed on the command promot the Getopt::Long should ignore all the rest of the switches. ( in any case if -h is typed the user wont be typing the rest of the switches so the module shoulndnt give an error on that)
Thanks for giving me time.

Replies are listed 'Best First'.
Re: how to make -h optional in GetOpt::Long
by tlm (Prior) on Jun 02, 2005 at 03:02 UTC

    What you have pairs up 'h=s' with a reference to the result of evaluating error_detect("h"). Try

    'h=s' => \&error_detect("h"),
    (note the ampersand).

    the lowliest monk

      Adding the ampersand does nothing if you keep the parameter. I don't believe a sub is appropriate here anyway -- they're meant to help parsing -- and it shouldn't be h=s either.

      Getopt::Long::GetOptions( 'u=s' => \$user, 'p=s' => \$passwd, 's=s' => sub { local *_ = \$_[1]; /^([^:]+):(\d+)$/ or die("Invalid format for option s.\n"); $host = $1; $port = $2; }, 'help' => \$help, # Will also handle -h ) or error_detect("3 Invalid commmand line options."); if ($help) { die("usage: ...\n"); }

      We've already answered this question for him.

        but keeping every thing aside. how do u make a switch optional in GetOpt::Long? in STD you use a semi colon to denote that the switch is optional what do u do in Long? what if i have more than 2 switches which are optional? how do i express them as optional in Long?