Parameters are passed to subroutines by setting global variables or through the default variable. Here is an example which demonstrates how the the default variable is used:
sub max
{
my $max= shift(@_);
foreach $ret (@_)
{
$max = $ret if $max < $ret;
}
return $max;
}
$bestday = max( $mon, $tue, $wed, $thu, $fri);
The default variable may contain a reference to a hash:
sub find_device_name
{
my $params = shift;
my $device = $$params{device};
if( $device)
{
delete $$params{device};
goto device_found;
}
...
device_found:
return " $device";
}
...
$buffer = find_device_name( \%params);
...
So far, the subroutines returned scalar variables. It is also possible to return an array:
sub1
{
...
return wantarray ? ( $a, $b, $c) : undef;
}
...
($x, $y, $z) = sub1();
...
The function wantarray returns 1, if the subroutine was called in a list context:
Note that subroutines may return an undefined value:
sub sub1
{
...
$ret_stat = $somevalue;
goto finish;
...
$ret_stat = undef;
goto finish;
...
finish:
return $ret_stat;
}
$ret = sub1();
if( defined $ret)
{
...
}
else {
print "Error\n";
}
The function caller returns information about the calling frame:
($package, $filename, $line) = caller;
There is an optional numeric argument to caller() which specifies the number of frames to be popped from the stack.