12.1.5 Passing References to a Subroutine Using Type Specification
12.1.5 Passing References to a Subroutine Using Type Specification
In Perl, it is possible to send the reference to a parameter to a function using the parameter type specification. To pass a parameter as a reference and not by value, we need to precede its type specification by a back slash (\). The following is a rewrite of the divide subprogram where the first “formal parameter” is passed by reference and the second “actual parameter” is passed by value. The two parameters are still passed to the subprogram in terms of the special list variable @_, but the first element of this list inside the subprogram is a reference to a scalar variable and the second is a scalar variable.
Program 12.5
use strict;
#Here, the first parameter must start with the $ character. The
#second parameter has to be a scalar, either a variable or a constant.
#A reference to the first parameter will be passed. The value of the
#second parameter is passed.
sub divide (\$$) {
my $result;
my ($num, $denom) = @_;
if ($denom == 0){
print "You are trying to divide by zero: $$num/$denom.\n";
}
else {
$result = $$num/$denom;
print "$$num/$denom = $result\n";
}
}
#main program
my ($num, $denom);
#Here, the first parameter to divide must start with the $ character
#first division
$num = 100; $denom = 10;
divide ($num, $denom);
divide ($num, 0);
#divide (100, 10) is an error because the first parameter doesn't start with $
We see that use of \ in front of the type specification for an parameter puts a restriction on how the function can be called. Here, since the first “formal parameter’s” type is specified as \$, the first “actual parameter” in any call to divide must start with the $ character. In other words, we cannot put a scalar value as the first “actual parameter.” The reference to the first parameter is sent to the subprogram. So, inside the body of the subprogram, the first element of the list @_ is a reference to a scalar variable. That is why, when we perform the addition, we need to dereference $num.
Dereferencing is done by using $$num. Since $num points to a scalar, to dereference we precede it with another $ character.
