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 (Chancellor) 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');"