How to address perl arguments
Wednesday, July 28th, 2010If you are using perl, you may find it necessary to take some command line arguments to your scripts. When that time comes, there is a very handy variable ARGV that contains the passed in arguments.
To get the total number of arguments passed into the script you will need to use the following:
$totcommandargs = #$ARGV + 1
is equal to the number of arguments passed in to the Perl script.
Note: you need to add one to the count to get the correct number of variables.
To address the variables you use the following to address the first argument: $ARGV[0]
will address the first argument
Since arrays are addressed by n-1, to get the first element you use 0 {zero}, for the second 1, for the third {2}, and so on.
$0 will give the name of the currently executing script.
#!/usr/bin/perl
$argcount = $#ARGV +1;
print "The script $0 has $argcount argumentsn";
for( $i = 0; $i < $argcount;$i++)
{
print $ARGV[$i] . "n";
}