Setting the default value using Params :: Validate if the undefined value is passed to

I am having trouble getting Params :: Validate to work the way I want.

#!/usr/local/bin/perl -w 
use strict;
use Params::Validate qw/:all/;
use Data::Dumper;

sub foo {
    my %args = validate(@_, {
        bar => {
            default => 99,
            # TODO - Somehow use a callback to return a default if undefined
            # ??!!?? 
            # callbacks => { call_me => sub { return 99 if !defined shift }},
        },
    });

    # $args{bar} //= 99; # Don't want to define default in 2 places

    print Dumper(\%args);
}
foo({ bar => undef });

So, how do I set / check undef in the args list and replace it with the default value Params :: Validate ??

+3
source share
1 answer

You need to set $ _ [0]:

call_me => sub { $_[0] = 99 if not defined $_[0] }

@_ is flattened with the parameters passed, so you can use this as a link to the original.

Moreover,

$args{bar} ||= 99;

there will be a reset bar, even if it is 0 or `` '' (empty string), which is not like what you want. Using

$args{bar} //= 99;

if you use perl 5.10 or later, do what you want.

, , , :

sub foo
{
    unshift @_, bar => undef;
    my %args = validate(@_,
                        {
                            bar => {
                                optional => 1,
                                callbacks => {
                                    call_me => sub { $_[0] = 99 unless defined $_[0] },
                                },
                            },
                        },
                       );
    print Dumper \%args;
}

, - .

+2

Source: https://habr.com/ru/post/1706768/


All Articles