Marcus
Marcus

Reputation: 315

Perl: Named parameters validation best practice

I am using named parameters in class method calls and was wondering if there is a best practice to make sure no unknown parameters are passed. Here's what I am doing

sub classmethod {
    my $self = shift;
    my %args = (
        "param1" => "default1",
        "param2" => "default2",
        @_
    )

    if (my @invalid = grep { !/^(param1|param2)$/ } keys %args) {
        croak "received unknown arg(s) ".join(",", @invalid)." from ".caller();
    }
}

Is that a proper way to go forward, or could this cause a performance problem?

Best, Marcus

Upvotes: 3

Views: 757

Answers (2)

Greg Nisbet
Greg Nisbet

Reputation: 6994

There are a lot of ways to pass parameters in Perl, and a lot of ways to validate them (or not).

If you are using the explicit default idiom anyway and want a light touch, then you can check that the number of keys in the hash are equal to the number of keys in the defaults. Getting the number of keys is a fast operation that doesn't depend on the size or contents of the hash table. If there is a key "in" @_ that isn't in %default, then %args will have more keys.

The disadvantage that this has over your current solution is that it doesn't tell you which key is unexpected.

sub classmethod {
    my $self = shift;
    my %args = (
        param1 => "default1",
        param2 => "default2",
        @_
    );
    keys %args == 2 or croak "received unknown arg. args: " . join(", ", keys %args);
}

Or do something like this to avoid having to change the number when you change the number of parameters.

sub classmethod {
    my $self = shift;
    my %default = (
        param1 => "default1",
        param2 => "default2",
    );
    my %args = (%default, @_);

    keys %args == keys %default or croak 'unknown arg' . join(", ", keys %args);
}

Upvotes: 1

Chris
Chris

Reputation: 729

You could use Params::Validate. Another option is Params::Check

If params are fixed, then its best to validate them during development, with the option to turn off validation when live.

Upvotes: 5

Related Questions