Perl Function Argument

by Geethalakshmi 2010-09-17 14:18:12

Perl Function Argument


To pass arguments or values to a sub routine, you place the variables with the '( )'s following the name of the subroutine. These variables are automatically placed in a variable '@_' that is private to the subroutine.

Within the subroutine, you can refer to the different elements of the array '@_' by using '$_[x]'. Where x = the element number. Thus if you called a subroutine as...

do_sub(value1, value2);

do_sub() {
print "@_"; # prints value1, value2
print "$_[0]"; # prints value1
print "$_[1]"; # prints value2
}

In re-writing the above sum_a_b routine to pass any variable names it would look like...

sub sum_a_b {
return $_[0] + $_[1]
}

print sum_a_b(3,4); # prints 7
$c = sum_a_b(5, 6); # prints 11

To handle unlimited or a variable list of passed arguments, you can use a foreach loop and the '@_' variable.

sub add {
$sum = 0;
foreach $_ (@_) {
$sum += $_;
}
return $sum;

$a = add(4,5,6); # $a = 15
print add(1, 2, 3, 4, 5); # prints 15
print add(1..5); # also prints 15 because 1..5 is expanded

Tagged in:

935
like
0
dislike
0
mail
flag

You must LOGIN to add comments