PERL subroutines
A subroutine may be declared as follows:
sub NAME BLOCK
Any arguments passed to the routine come in as array @_,
that is ($_[0], $_[1], ...). The array @_ is a local array,
but its values are references to the actual scalar parameters.
The return value of the subroutine is the value of the last
expression evaluated, and can be either an array value or a scalar
value. Alternately, a return
statement may be used to specify the returned value and
exit the subroutine. To create local variables see the
local operator.
A subroutine is called using the do-operator or the & operator.
For example,
sub MAX {
local($max) = pop(@_);
foreach $foo (@_) {
$max = $foo if $max < $foo;
}
$max;
}
...
$bestday = &MAX($mon,$tue,$wed,$thu,$fri);
This is another example.
# get a line, combining continuation lines
# that start with whitespace
sub get_line {
$thisline = $lookahead;
line: while ($lookahead = <STDIN>) {
if ($lookahead =~ /^[ \^\t]/) {
$thisline .= $lookahead;
} else {
last line;
}
}
$thisline;
}
$lookahead = <STDIN>; # get first line
while ($_ = do get_line()) {
...
}
Use array assignment to a local list to name your formal arguments:
sub maybeset {
local($key, $value) = @_;
$foo{$key} = $value unless $foo{$key};
}
This also has the effect of turning call-by-reference into
call-by-value, since the assignment copies the values.
Subroutines may be called recursively. If a subroutine is
called using the & form, the argument list is optional. If
omitted, no @_ array is set up for the subroutine; the @_ array
at the time of the call is visible to subroutine instead.
do foo(1,2,3); # pass three arguments
&foo(1,2,3); # the same
do foo(); # pass a null list
&foo(); # the same
&foo; # pass no arguments--more efficient
Click here to go back to the Perl index
|