Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Setting default values in getopts

by neilwatson (Priest)
on Mar 27, 2002 at 14:55 UTC ( [id://154678]=perlquestion: print w/replies, xml ) Need Help??

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

Givers of wisdom and knowledge please consider my humble questions:

How does one set default values of command line arguements?

use Getopt::Std; my %opt; my $opt{d} = "x"; my $opt{a} = "0"; my $opt{s} = "0"; my $opt{e} = "x"; getopts("dase:", \%opt);

Using something like this returns a syntax error at my $opt{d}="";. What have I done wrong?

Neil Watson

Replies are listed 'Best First'.
(jeffa) Re: Setting default values in getopts
by jeffa (Bishop) on Mar 27, 2002 at 15:01 UTC
    You can't redeclare a variable with my as you are doing. In fact, the better way to declare %opt is with use vars, like so:
    use vars qw(%opt); $opt{d} = "x"; $opt{a} = "0"; $opt{s} = "0"; $opt{e} = "x"; getopts("dase:", \%opt);
    Good luck!


    (the triplet paradiddle with high-hat)
Re: Setting default values in getopts
by Fletch (Bishop) on Mar 27, 2002 at 15:05 UTC

    Aside from jeffa's point about you re-my'ing things, you might want to use something like this instead of multiple assignments:

    my %opt = ( d => "x", a => 0, s => 0, e => "x", );
Re: Setting default values in getopts
by maverick (Curate) on Mar 27, 2002 at 17:29 UTC
    jeffa is quite's what I tend to do, since the next natural thing is to assign each option out into a meaningfully named scalar
    my %opts; getopts("d:a:s:e:", \%opt); my $Directory = $opts{'d'} || '/home/maverick'; my $Address = $opts{'a'} || ''; my $Silent = $opts{'s'} || 0; my $Extended = $opts{'e'} || 0;
    This way I don't have to remember what's in $opts{'d'} and neither does whoever reads my code later. Plus the defaults are really easy to spot.

    perl -l -e "eval pack('h*','072796e6470272f2c5f2c5166756279636b672');"

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://154678]
Approved by root
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (5)
As of 2024-04-23 20:18 GMT
Find Nodes?
    Voting Booth?

    No recent polls found