Beefy Boxes and Bandwidth Generously Provided by pair Networks Frank
Welcome to the Monastery
 
PerlMonks  

Getopt::Long and default number

by mrborisguy (Hermit)
on Jul 19, 2005 at 14:27 UTC ( [id://476217]=perlquestion: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.

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 14: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 14: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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://476217]
Approved by Eimi Metamorphoumai
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.