Google News
logo
Perl - Interview Questions
How are parameters passed to subroutines in Perl?
In Perl, all input or actual parameters of the subroutine are stored in an array ‘@_’. In other words, array @_ is used as an alias for subroutine arguments.
 
Let’s demonstrate this with an example :
print &sum(1..4),”\n”;
sub sum{
my $sum = 0;
for my $i(@_){
$sum += $i;
}
return $sum;
}
In this example, we are calculating the sum of elements 1 to 4. We pass these elements as a range to a subroutine. In the subroutine code, @_ that contains parameters is iterated to find the sum and then the sum is returned.
Advertisement