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

Hi, I'm new to Perl and so I'm just starting to understand its power. I'm trying to run a perl script so that users can call it and pass certain arguments in. e.g. ascript -d db1 -i inst1 or ascript -ddb1 -i inst1 My solution is okay but as I'm trying to get a feel of perl I'm guessing there is a better way. ( A case of right answer but probably not best perl solution). I'm after advice really and getting into the perl programmers frame of mind rather than a C developer.
... cut ... my $str_arg = join " ",@ARGV; #remove spaces $str_arg =~ s/\s//g; @args= split /-/, $str_arg; shift @args; for my $arg (@args) { my $opt = substr($arg,0,1); switch ($opt) { case /d/ { #this is taking the value off. $options{$opt}=$arg; print "This is a database $options{$opt}\n"; } case /i/ { $options{$opt}=$arg; print "This is an instance $options{$opt}\n"; } else { print "Error arg not recognised!!!\n"; } } }
Thanks, DanDan Thanks for all your great help... The solutions and ideas and pointers are spot on. Thanks, DanDan.

Replies are listed 'Best First'.
Re: Command Prompt arguments.
by slife (Scribe) on Jun 21, 2004 at 11:50 UTC

    DanDan, welcome to the Perl community.

    Others have already pointed out that there are several modules available that handle command line options.

    However, since you describe yourself as both a Perl novice and a C-programmer, here are some comments that I hope will be helpful:

      Excellent recommendations!

      I'll just add a few things. If you're not familiar with the excellent documentation that is included with perl, it's called the 'perldocs'. You can get started by doing 'perldoc perl' at a command prompt.

      As far as books are concerned, I would also highly recommend 'Programming Perl' 3rd edition. And high on my list are 'Learning Perl' and 'Perl Cookbook'.

      HTH.

Re: Command Prompt arguments.
by borisz (Canon) on Jun 21, 2004 at 10:54 UTC
Re: Command Prompt arguments.
by eserte (Deacon) on Jun 21, 2004 at 10:56 UTC
    Usually you should use one of the Getopt:: modules. Here's the solution with Getopt::Long (untested):
    use Getopt::Long; GetOptions(\%opt, "d=s", "i=s") or die "usage..."; # the options are now in $opt{d} and $opt{i}
Re: Command Prompt arguments.
by husker (Chaplain) on Jun 21, 2004 at 15:18 UTC
    For what you are doing, I recommend Getopt::Std.

    In fact, this recent Code I posted uses Getopt::Std for some required and optional command-line arguments. Hope it's illustrative for you.

    Edit: Added link to example code.