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

hi guys

another newbie question: how can i write my perl script so that it accepts command line arguments when called?

sorta like when you type scp at your shell with all the switches and other arguments... and if you don't input any arguments or you enter an incorrect argument/no. of arguments, a 'usage' message pops up... i think i'd have to use the @ARGV array but i can't think of how to start searching for an article or documentation that may help... be gentle :)

thanks

Replies are listed 'Best First'.
Re: command line arguments?
by cjf (Parson) on May 23, 2002 at 08:57 UTC

    You can use shift or read from @ARGV like so...

    use strict; my $arg = shift; my @args = @ARGV; print "$arg\n"; foreach (@ARGV) { print $_, "\n"; }

    Hope that helps :).

Re: command line arguments?
by ajt (Prior) on May 23, 2002 at 09:07 UTC
    There are several ways to do this.

    For very simple uses you can simply shift the values one at a time of the @ARGV array. This is very easy to do for short throw-away applications, but becomes an unmanagable mess for anything more complex. For example:

    #!/usr/bin/perl my $argument_1 = shift; die "Invalid input" unless $argument_1;

    A better approach is to use one of the many Getopt modules. I think that both Getopt::std and Getopt::Long have both been part of the core Perl for some time, so you should have them on your system already.

    For example:

    #!/usr/bin/perl use Getopt::Std; getopt('oDI'); print "\nOption o = $opt_o";

    You should find that perldoc will give you the full details of both modules, and any additional ones you install.

      ok thanks guys... turns out a simple shift and some error-checking was enough... i'm not that advanced into perl to take a look at modules yet but thanks all the same dave, ajt... i was only looking for a quick solution since the core of the script is going to be a tough one (so expect more questions from me :-))... at least it's a comfort to know that there are modules to handle this for more complicated arguments

      cheers!
Re: command line arguments?
by dash2 (Hermit) on May 23, 2002 at 09:00 UTC
      Also, you might want to take a peek at Pod::Usage for creating help messages with variable verbosity.

      This might be overkill for your program, but I found it very useful for larger tools.

      -- Joost downtime n. The period during which a system is error-free and immune from user input.
(MeowChow) Re: command line arguments?
by MeowChow (Vicar) on May 23, 2002 at 09:56 UTC
    Aside from the methods already given, you may also want to take a look at perlrun's section on the -s switch, which is nice for quick hacks.
       MeowChow                                   
                   s aamecha.s a..a\u$&owag.print
Re: command line arguments?
by neilwatson (Priest) on May 23, 2002 at 15:37 UTC