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

Passing by Named Parameter

Problem

You want to make a function with many parameters easy to invoke so that programmers remember what the arguments do, rather than having to memorize their order.

Solution

Name each parameter in the call:

thefunc(INCREMENT => "20s", START => "+5m", FINISH => "+30m");
thefunc(START => "+5m", FINISH => "+30m");
thefunc(FINISH => "+30m");
thefunc(START => "+5m", INCREMENT => "15s");

Then in the subroutine, create a hash loaded up with default values plus the array of named pairs.

sub thefunc {
    my %args = ( 
        INCREMENT   => '10s', 
        FINISH      => 0, 
        START       => 0, 
        @_,         # argument pair list goes here
    );
    if ($args{INCREMENT}  =~ /m$/ ) { ..... }
}

Discussion

Functions whose arguments require a particular order work well for short argument lists, but as the number of parameters increases, it’s awkward to make some of them optional or have default values. You can only leave out trailing arguments, never initial ones.

Having the caller supply value pairs is a more flexible approach. The first element of the pair is the argument name, and the second is its value. This makes for self-documenting code, because you can see the parameters’ intended meanings without having to read the full function definition. Even better, programmers using your function no longer have to remember the order of the arguments and can omit any arguments.

This works by having the function declare a private hash variable to hold the default parameter values. Put the current arguments, @_ , after the default ...

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