Monday, December 05, 2005
Perl: Subroutines
What's a language without subroutines? Perl subroutine definitions take
the following form:
sub NAME {
STATEMENTS;
}
Unlike C, subroutines are not typed. All subroutines take a list as
arguments. A subroutine can return values values in either a list or
scalar context.
Unlike Pascal, subroutine definitions cannot be nested. Actually, they can
be defined anywhere that is not in a block. This will be used below.
Unlike Fortran, there is no distinction between subroutines and functions.
I'll try to stick to using "subroutine", but the terms are
interchangeable.
Arguments to the subroutine are contained in the special array @_ (at
underscore)
Oh gee, now we need to worry about variable scoping...
For the purposes of this tutorial, let's consider all variables global.
Recursion is possible - but beyond this tutorial.
In perl, subroutines are invoked differently than the builtins
&NAME(arg1,arg2,etc);
# - or - (if the subroutine takes no arguments.
&NAME;
# return values are used just like anyother value
$loudestInstrument = &measureLoudest(@allInstruments);
--------------------------------------------------------------------------------
Example
# define an error routine:
sub error {
($message) = @_;
print("<b>ERROR:<b>",
$message,
"<p>Contact the author of the previous page for assistance\n");
exit(0);
}
if ( ! $recipient ) {
# the form did not have a to field
# modify this text appropriately
&error("No Return Address");
}
Note how the definition of the subroutine doesn't affect the flow of our
program.