O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Accessing Subroutine Arguments

Problem

You have written a function and want to use the arguments supplied by its caller.

Solution

All values passed as arguments to a function are in the special array @_ . Thus, the first argument to the function is in $_[0], the second is in $_[1], and so on. The number of arguments is therefore scalar(@_).

For example:

sub hypotenuse {
    return sqrt( ($_[0] ** 2) + ($_[1] ** 2) );
}

$diag = hypotenuse(3,4);  # $diag is 5

Your subroutines will almost always start by copying arguments into named private variables for safer and more convenient access:

sub hypotenuse {
    my ($side1, $side2) = @_;
    return sqrt( ($side1 ** 2) + ($side2 ** 2) );
}

Discussion

It’s been said that programming has only three nice numbers: zero, one, and however many you please. Perl’s subroutine mechanism was designed to facilitate writing functions with as many —or as few—elements in the parameter and return lists as you wish. All incoming parameters appear as separate scalar values in the special array @_ , which is automatically local to each function (see Section 10.13). To return a value from a subroutine, use the return statement with an argument. If there is no return statement, the return value is the result of the last evaluated expression.

Here are some sample calls to the hypotenuse function defined in the Solution:

print hypotenuse(3, 4), "\n";               # prints 5

@a = (3, 4);
print hypotenuse(@a), "\n";                 # prints 5

If you look at the arguments used in the second call to hypotenuse

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required