Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

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
watson-wilson.ca

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!

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (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 right...here'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'} || 'somewhere@overtherainbow.com'; 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.

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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (9)
As of 2024-04-19 07:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found