4. Functions

We already encountered some of Perl's built-in functions. Perl enables us to define our own functions using Perl code. Whenever you use a piece of code more than once in a program, it is a good idea to make it into a function. That way, you won't have to change it in more than one place.

In Perl, every function accepts an array of arguments and returns an array of return values. The arguments (also known as "parameters") can be found in the @_ variable. This variable is magical and need not and should not be declared with my. In order to return values from a function, one can use the return keyword.

To declare a function use type sub function_name { at the beginning and a } at the end. Everything in between, is the function body.

Here's an example, for a function that returns the maximum and the minimum of an array of numbers.

use strict;
use warnings;

sub min_and_max
{
    my (@numbers);

    @numbers = @_;

    my ($min, $max);

    $min = $numbers[0];
    $max = $numbers[0];

    foreach my $i (@numbers)
    {
        if ($i > $max)
        {
            $max = $i;
        }
        elsif ($i < $min)
        {
            $min = $i;
        }
    }

    return ($min, $max);
}

my (@test_array, @ret);
@test_array = (123, 23 , -6, 7 , 80, 300, 45, 2, 9, 1000, -90, 3);

@ret = min_and_max(@test_array);

print "The minimum is ", $ret[0], "\n";
print "The maximum is ", $ret[1], "\n";

And here's another one for a function that calculates the hypotenuse of a right triangle according to its other sides:

use strict;
use warnings;

sub pythagoras
{
    my ($x, $y);

    ($x, $y) = @_;

    return sqrt($x**2+$y**2);
}

print "The hypotenuse of a right triangle with sides 3 and 4 is ",
    pythagoras(3,4), "\n";

Written by Shlomi Fish