Perl: Named parameters validation best practice

怎甘沉沦 提交于 2019-12-05 21:27:22

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.

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!