Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

using arguments when running a script

Status
Not open for further replies.
Jul 31, 2001
37
0
0
US
Can perl take arguments off of the command line and choose different variables based on what argument is given. for example can.

showan.pl -h LA

could that call a perlscript which has a bunch of variables in it and based on the "LA" given after the -h call the variable $LA = "la1-7200"

i'm trying to use one perl script that has multiple hosts in it as variables. i want the same script to run on different hosts depending on the -h argument? Any and all help is appreciated. i'm open to other suggestions as well.


Mark
 
Hi Mark,

Yes. Perl can take values from the command line, like this.

my $switch = shift;

That takes the first argument, in your example that would be -h

my $host = shift;

That takes the second argument, in your example that would be LA

Why do you need a variable *called* $LA? You can do that, but it's fiddly and not usually needed.
Mike
________________________________________________________________

"Experience is the comb that Nature gives us, after we are bald."

Is that a haiku?
I never could get the hang
of writing those things.
 
As well as shift, you can also use the special array @ARGV to access command line args. $ARGV[0] is the first argument in the command line. A note on this is that to check for no command line arguments you must check to see that $#ARGV is < 0. i.e. $#ARGV is the number of arguments - 1.

These are just extra ramblings though....use shift. :) --Derek

&quot;Fear not the storm for this is where we grow strong.&quot;
 
WOW that was so easy. Thanks to both of you for your help.

How many arguments can i call from the command line like this

Mark
 
If you are going to be using several command line switches then it's more practical to use a Perl module that will parse switches for you. Either Getopt::Std or Getopt::Long is simple to use. For example Getopt::Std will set a variable (or a hash key if you pass it a hashref) that contains the value after the switch (or 1 if the switch doesn't take an argument). Here's an example:
Code:
use strict;
use Getopt::Std;

my $LA;
our ($opt_h, $opt_s);

getopt('hs');

if (defined $opt_h) {
        $LA = $opt_h;
}
if (defined $opt_s) {
        # so something here for -s
}
Then none of the switches or their arguemnts appear in @ARGV, only true command line arguments do.

 
Excellent!
I tried all the suggestion and was able to make them all work. The help here is invaluable. Thanks again
Mark
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top