Conditional parameter passed using MooseX :: Params :: Validate

I work a lot with packages Moosein Perl that use MooseX::Params::Validateto define an interface. These interfaces are usually quite flexible and allow you to use several optional parameters. Unfortunately, this is Perl, so the types of returned data will change depending on additional parameters, and there is an advantage for passing optional parameters in most cases when they are defined in the caller. The various methods exported from MooseX::Params::Validateare used in this code base, so due to the different methods of processing the package, the parameters undefthat I cannot pass will be elegant anyway. I usually use the following method, but in the reviews it is a lot, and I would like to ask if there is another way to achieve this flexibility.

use strict;
use warnings;

my $bar;

Foo->foo({
    foo => 'I, Foo need a VERY flexible interface. ',
    $bar ? ( bar => $bar ) : ()
});

$bar = "Very flexible...";

Foo->foo({
    foo => 'I, Foo need a VERY flexible interface. ',
    $bar ? ( bar => $bar ) : ()
});

package Foo;

use Moose;
use MooseX::Params::Validate;

sub foo {
    my $self = shift;
    my ( $foo, $bar ) = validated_list(
      \@_,
      foo => { isa => 'Str' },
      bar => { isa => 'Str', optional => 1 },
    );

    print $foo . $bar . "\n";
}

1;

defined - , //, , .

caller , ( ) , , undef.

+4
2

, , , undefined . undefined - MooseX::Params::Validate::validated_list(). :

use strict;
use warnings;

my $bar;

Foo->foo({
    foo => 'I, Foo need a VERY flexible interface. ',
    bar => $bar
});

package Foo;

use Moose;
use MooseX::Params::Validate ();

sub foo {
    my $self = shift;

    my ( $foo, $bar ) = validated_list(
      \@_,
      foo => { isa => 'Str' },
      bar => { isa => 'Str', optional => 1 },
    );

    $bar //= 'undef';  # Just to avoid printing warning: Use of uninitialized value 
    print $foo . $bar . "\n";
}

sub validated_list {
    for (keys %{ $_[0]->[0] } ) {
        delete $_[0]->[0]{$_} if !defined $_[0]->[0]{$_};
    }
    return MooseX::Params::Validate::validated_list( @_ );
}
1;
0

Maybe , . MooseX:: Params:: Validate undef , Str, , . undef , , , , ( ).

sub foo {
    my $self = shift;
    my ( $foo, $bar ) = validated_list(
      \@_,
      foo => { isa => 'Str' },
      bar => { isa => 'Maybe[Str]', optional => 1 }
    );

    print $foo . $bar . "\n";
}

Maybe [Str], undef, undef, , .

Maybe[`a] accepts either `a or undef.

http://search.cpan.org/dist/Moose-2.0604/lib/Moose/Manual/Types.pod

0

All Articles