Perl FAQ: How do I access the arguments that have been passed to my subroutine or function?
Answer: The special array @_ holds the values that are passed into a Perl subroutine/function, and you use that array to access those arguments. The first argument is represented by the variable $_[0], the second argument is represented by $_[1], and so on.
It may also help to know that number of elements passed in to your subroutine is given by the value of scalar(@_).
Perl example: Processing function arguments
In my sample Perl code shown below, I demonstrate how to determine the number of arguments passed in to my subroutine, and then print out the first two arguments that are passed in:
#!/usr/bin/perl
# define the subroutine
sub demo
{
$num_args = scalar(@_);
print "Number of arguments is $num_args\n";
print "First arg is $_[0]\n";
print "Second arg is $_[1]\n";
}
# call the subroutine
&demo("hello", "world");
Here’s a slightly more real-world example. In this example I validate the number of arguments passed into my function, and if there are not exactly two elements I tell my program to die. (You never have to do this, I’m just showing how to do it.) After that I also show how to use the my operator so the two new variables $arg1 and $arg2 are created in a local scope, and can't be seen outside of my demo function.
Here’s the example Perl code:
#!/usr/bin/perl
# define the subroutine.
# slightly more real-world.
# use the "my" operator to access the variables in local scope.
sub demo
{
die "Wrong number of args" if (scalar(@_) != 2);
my $arg1 = $_[0];
my $arg2 = $_[1];
print "$arg1, $arg2\n";
}
# call the subroutine
&demo("hello", "world");

