Contents /
Previous /
Next
Subroutines (Functions): &
Perl does not distinguish between subroutines and functions.
A subroutine can return values values in either a list or scalar context.
All subroutines take a list as arguments.
Recursion is possible.
sub NAME
{
STATEMENTS;
}
Subroutines are invoked using the &
(differently than the builtins):
&NAME(arg1,arg2,etc);
Or if the subroutine takes no arguments:
&NAME;
Return values are assigned like any other value:
$state = &init(@data);
Without explicit return statement a subroutine
return the last assigned value.
Example:
sub init
{
print @_."\n";
print $_[0]." and ".$_[1]."!";
return "\nok.\n";
}
$state = init( "me", "you" );
print $state;
Output:
2
me and you!
ok.