Params :: Validate,如何要求两个参数之一?

时间:2012-11-14 01:03:43

标签: perl params

如果我有一个方法接受两个命名参数中的一个或另一个,其中一个必须存在,是否有办法用Params :: Validate来处理它?<​​/ p>

  $store->put( content_ref => $stringref );

  $store->put( path => $path_to_file );

我没有在文档中看到它,但它似乎是一个明显的用例,所以我想我应该问。

1 个答案:

答案 0 :(得分:3)

您可以使用callbacks来实现这些目标:

#!/usr/bin/env perl

use strict;
use warnings;

package My::Class;

use Params::Validate;
use YAML;

sub new { bless {} => shift }

sub _xor_param {
    my $param = shift;
    return sub { defined($_[0]) and not defined($_[1]->{$param}) }
}

my %validation_spec = (
    content_ref => {
        'default' => undef,
        callbacks => {
            "Provided only if no 'path' is given"
                => _xor_param('path')
        },
    },
    path => {
        'default' => undef,
        callbacks => {
            "Provided only if no 'content_ref' is given"
                => _xor_param('content_ref')
        },
    },
);

sub put {
    my $self = shift;
    validate(@_, \%validation_spec);
    print Dump \@_;
}

package main;

my $x = My::Class->new;

$x->put(path => 'some path');
$x->put(content_ref => \'some content');
$x->put(path => 'another_path', content_ref => \'some other content');

输出:

---
- path
- some path
---
- content_ref
- !!perl/ref
  =: some content
The 'content_ref' parameter ("SCALAR(0xab83cc)") to My::Class::put did not pass
the 'Provided only if no 'path' is given' callback
 at C:\temp\v.pl line 37
        My::Class::put(undef, 'path', 'another_path', 'content_ref', 
'SCALAR(0xab83cc)') called at C:\temp\v.pl line 47