http://www.perlmonks.org?node_id=349590


in reply to how to access the commandline arguments?

Arguments passed to the script are stored in the array @ARGV. To know how many arguments are in @ARGV there are two ways:
my $count = @ARGV; print $count;
OR you can use the special variable $#ARGV which contains the index number of the last array element. That is, if you have 4 elements in your array the last index number is 3.

To turn @ARGV this into variables try something like the below at the beginning of your script:
if (@ARGV < 3) { die "use: script var1 var2 var3\n"; } else { my ($var1, $var2, $var3) = @ARGV; } ## then use $var1, $var2 and $var3 in your program
This has the effect of ensuring your program is passed enough variables.

Alternatively you could do something like the below if you want to set defaults to variables if they aren't passed to the script:
my ($stream, $path, $rturn, $depth, $display) = @ARGV; $stream = \*STDOUT unless @_ > 0; $path = cwd unless @_ > 1; $rturn = 'all' unless @_ > 2; $depth = -1 unless @_ > 3; $display = 'rel_file' unless @_ > 4;
This means if someone calls your program without arguments then a default value is used.

Its also common to use "shift" to grab the next element in @ARGV.
my $nextvar = shift @ARGV;
Or you can loop through @ARGV like any other array.
for my $this (@ARGV) { print "$this\n"; }
In fact you can treat @ARGV pretty much like any array and "push", "shift", "unshift" or any other array function as you please.

Someone also mentioned using <> the "null filehandle". Usually you can use <FILEHANDLE> to input the contents of an open filehandle. Using just <> means if you pass filenames on the commandline when calling your scripts then these are taken as files to open and read one by one until they are exhausted. If you don't pass any filenames then <> just defaults to reading the STDIN. For example, if you call the below code with: myscript.pl file1 file2 file3
while (<>) { print "$_\n"; }
... then you see the entire contents of each file output to the screen. If you didn't pass any files then anything passed to STDIN is used.

On top of all this you can get a lot more functionality by using the "Getopt::Long" module as others suggested. Its worth taking the time to get to know this module. If you need an example of how to use this let me know and I'll include one.

Dean
The Funkster of Mirth
Programming these days takes more than a lone avenger with a compiler. - sam
RFC1149: A Standard for the Transmission of IP Datagrams on Avian Carriers