Book HomePerl CookbookSearch this book

10.7. 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 values, so the actual arguments will override the defaults because of the order of the values in the assignment.

See Also

Chapter 4, Arrays


Previous: 10.6. Detecting Return ContextPerl CookbookNext: 10.8. Skipping Selected Return Values
10.6. Detecting Return ContextBook Index10.8. Skipping Selected Return Values

Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.