Subroutines
Subroutines are declared using one of these forms:
sub name {block} sub name (proto) {block}
Prototypes allow you to put constraints on the arguments you provide to your subroutines.
You can also create anonymous subroutines at run-time, which will be available for use through a reference:
$subref = sub {block};
Calling Subroutines
The ampersand (&) is the identifier used to
call subroutines.
Most of the
time, however, subroutines can be used in an
expression just like built-in functions.
To call subroutines directly:
name(args); # & is optional with parentheses name args; # Parens optional if predeclared/imported &name; # Passes current @_ to subroutine
To call subroutines indirectly (by name or by reference):
&$subref(args); # & is not optional on indirect call
&$subref; # Passes current @_ to subroutine
Passing Arguments
All arguments to a subroutine are passed as a single, flat list of scalars, and return values are returned the same way. Any arrays or hashes passed in these lists will have their values interpolated into the flattened list.
Any arguments passed to a
subroutine come in as the array @_.
You may use the explicit return statement to return
a value and leave the subroutine
at any point.
Passing References
If you want to pass more than one array or hash into or out of a function and have them maintain their integrity, then you will want to pass references as arguments. The simplest way to do this is to take your named variables and put a backslash ...