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

I've started using Getopt::Long for a little script I'm creating. I'm having trouble figuring out how to give an option a default value if it is specified. For example:

shell$ progname $opt == 0 shell$ progname --opt $opt == 100 shell$ progname --opt 7 $opt == 7

Or more verbosely, if --opt isn't specified, I want it to be 0. If --opt is specified, but not given any number, I want $opt to hold 100, and if --opt is specified with a number, I want $opt to hold the number specified.

This is probably really easy, but I must be missing it. Has anybody done this before?

    -Bryan

Replies are listed 'Best First'.
Re: Getopt::Long and default number
by jimbojones (Friar) on Jul 19, 2005 at 18:41 UTC
    Hi

    I think you want the ":" signifier when identifying your options. This says the value for the option is optional. If the option is present without a value, it takes the number indicatied after the ":" ; otherwise it takes the user-supplied value. This is in the POD in the section "Summary of Option Specifications"

    use Getopt::Long; my $opt = 0; GetOptions ("opt:100" => \$opt ); print "Opt is:\t$opt\n";
    My test runs give:
    >opt.pl --opt Opt is: 100 >opt.pl --opt 7 Opt is: 7 >opt.pl Opt is: 0
    HTH

    - j

      Bingo! Thanks! ++

          -Bryan

Re: Getopt::Long and default number
by izut (Chaplain) on Jul 19, 2005 at 18:49 UTC
    Try this:
    my $opt = "0"; $result = GetOptions ("opt:s" => \$opt,); $opt = 100 if ($opt eq "");
    I'm pretty sure there are some better way to perform this task, but can't figure out how right now.

    surrender to perl. your code, your rules.