Perl Information Center Tutorials - Subroutines
These tutorials were written to help you get a quick, but thorough, understanding of Perl -
the scope of the language as well as it's specific capabilities.
| Beginners
| Built-In Functions
| Advanced
| CGI Applications
|
|
|
|
|
|
Subroutines
In Perl, a programmer can name a block of code which can be executed
by simply calling out that name. These named blocks of code are
called subroutines and look like this (the line numbers in this example
are for reference only).
1 $a = &mysub; # $a is assigned the sub return value
2 $a = &mysub (1,2,3); # three arguments passed to sub
3 sub mysub { # subroutine definition
4 $arg1 = @_[0]; # not recommended
5 ($arg1, $arg2) = @_; # common way to read arguments
6 print 'hello';
7 return 7'; # value 7 is returned to calling expression
8 } # end of subroutine code block
9 $a = mysub; # & is optional since sub now exists
A subroutine is called simply by treating the subroutine as a
function whose name starts with & - as shown in line 1 of the
code example above.
Subroutine Location
A subroutine may be placed anywhere in the Perl program. If a line
of code calls a subroutine that is found later in the program,
the & is required. If the subroutine precedes the line of code that
calls it, the & is optional. However, it is considered good practice
to use the & at all times.
Arguments
When a subroutine is defined, no arguments are included in the
definition. When calling a subroutine, however, multiple values
may be passed to the subroutines, as in line 2 of the example above.
The arguments are made available within the special array variable @_.
above. Any of the Perl array functions may be applied to the @_ variable
to access the arguments.
If @ array is modified directly, the variables from the main scripts that
were used to pass values into the subroutine are also changed. But if you
copy elements (line 4) into local variables within the subroutine, the
variables in the main script are not modified.
Return Values
When a subroutine is called it returns the value of the last expression
evaluated. Or you may use a return statement (line 7) to explicitly
specifiy a return value. A return statement without a value returns undef.
Variable Scope
Global variables may be accessed within a subroutine. Also, variables
defined in subroutines are global unless declared using 'my'. If not
declared using 'my', subroutine variables may be accessed from the main program.
If you have suggestions or corrections to this page, please let me know.
|