【问题标题】:Params::Validate, how to require one of two parameters?Params::Validate,如何要求两个参数之一?
【发布时间】:2012-11-14 01:03:43
【问题描述】:

如果我有一个方法采用两个命名参数中的一个或另一个,其中一个必须存在,有没有办法用 Params::Validate 来处理它?

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

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

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

【问题讨论】:

    标签: perl params


    【解决方案1】:

    您可以使用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');
    

    输出:

    --- - 小路 - 一些路径 --- - content_ref - !!perl/ref =:一些内容 My::Class::put 的 'content_ref' 参数 ("SCALAR(0xab83cc)") 未通过 '仅在没有给出'路径'时提供'回调 在 C:\temp\v.pl 第 37 行 我的::Class::put(undef, 'path', 'another_path', 'content_ref', 'SCALAR(0xab83cc)') 在 C:\temp\v.pl 第 47 行调用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-15
      • 1970-01-01
      • 2016-09-25
      • 2015-07-15
      • 2011-07-27
      • 2012-06-24
      • 2020-05-23
      • 2021-12-18
      相关资源
      最近更新 更多