Databases Reference
In-Depth Information
Writing Your Own Perl Functions
As we've seen, a function is a statement such as
print( )
or
open( )
that performs an
operation for your program. Functions can take arguments within parentheses, and
can return a value.
You can define your own functions in Perl. Sometimes, you might want to perform a
task in several places of your program, such as to repeatedly display messages or per-
form calculations. You can define your own function to perform the task and then call
the function whenever you need the task to be performed.
Example 16-10 is a program with two small functions: one called
sum( )
to calculate
the sum of a list of numbers, and the other called
average( )
to average a list of numbers.
The
average( )
function uses the
sum( )
function in its calculations.
Example 16-10. Perl script with functions to sum and average numbers
#!/usr/bin/perl
use strict;
print "\nThe total is: ", sum(1, 5, 7);
print "\nThe average is: ", average(1, 5, 7);
# Function to calculate the sum of all the numbers passed to it
sub sum
{
my $Total=0;
while(my $value=shift)
{
$Total+=$value;
}
return $Total;
}
# Function to calculate the average of all the numbers passed to it
# This function calls the sum function internally.
sub average
{
return sum(@_)/(@_);
}
The
sum( )
function uses the
shift
keyword to iterate through the provided values one
by one, assigning them in turn to the
$value
variable. When all the values have been
seen and added to the
$Total
, the function returns the
$Total
value to the part of the
program that called it. This means that
sum(1, 5, 7)
has the value of
$Total
, which is
13.
The special array
@_
contains all the values passed to the function when it is called. The
average( )
function passes this list—in this example
1, 5, 7
—to the
sum( )
function
to get the total, and then divides this total by the number of values in the list, given by
the array name
@_
. Finally, the statement returns the resulting average: