perlsubroutine

How can I pass optional parameters to a Perl function?


I want to pass several parameters, one of which is optional, to a function. The only way to do it that I know is using a list (@) as a parameter. Thus, it contents nothing or one element (will never be undef), so that I can use the following code:

sub someFunction($$@) {
    my ($oblig_param1, $oblig_param2, $option_param) = @_;

    # ...
}

This code works, but I feel that maybe it's not the best workaround. Are there any other ways to do it?


Solution

  • You can use a semicolon in the prototype to indicate the end of the required parameters:

    sub someFunction($$;$) {
      my ( $oblig_param1, $oblig_param2, $option_param ) = @_;
      ...
    }
    

    The ; is optional before a @ or %, which, according to the docs, "gobbles up everything else".

    As DVK points out in a comment (and TLP emphasizes in another answer here), you are probably best off simply avoiding prototypes:

    sub someFunction {
      my ( $oblig_param1, $oblig_param2, $option_param ) = @_;
      ...
    }
    

    Perl prototypes have their uses (mostly to supply implicit context coercion to arguments, as Perl's built-in functions do). They should not be used as a mechanism to check that function are called with the correct number and type of arguments.