Understanding Perl's Special Variables - Getting Into An Argument (
Page 5 of 11 )
Perl comes with some very interesting variables specifically designed to
store input arguments, for both scripts and subroutines. The first of these
is the special @ARGV array, which contains a list of all the command-line
arguments passed to the Perl program; each argument is indexed as an
element of the array. Consider the following example, which demonstrates:
#!/usr/bin/perl
# get length of argument list
$num = @ARGV;
# iterate and print arguments
for ($x=0; $x<$num; $x++)
{
print "Argument " . ($x+1) . " is $ARGV[$x]\n";
}
Here's an example of the output (I called this script with the command-line
arguments "red 5px Arial"):
Argument 1 is red
Argument 2 is 5px
Argument 3 is Arial
Perl also comes with a variable named @_, which contains arguments passed
to a subroutine, and which is available to the subroutine when it is
invoked. The value of each element of the array can be accessed using
standard scalar notation - $_[0] for the first element, $_[1] for the
second element, and so on.
In order to illustrate, consider the following example:
#!/usr/bin/perl
# define a subroutine
sub add_two_numbers
{
$sum = $_[0] + $_[1];
return $sum;
}
$total = &add_two_numbers(3,5);
print "The sum of the numbers is $total\n";
In the example above, once the &add_two_numbers subroutine is invoked with
the numbers 3 and 5, the numbers are transferred to the @_ variable, and
are then accessed using standard scalar notation within the subroutine.
Once the addition has been performed, the result is returned to the main
program, and displayed on the screen via the print() statement.