@_ in a sub
use Params::Validate qw(:all);
sub foo {
#my $self = shift; # shift $self off first if OO
my ($name, $age ) = validate_pos(@_,
{
type => SCALAR,
callbacks => {
'min_length' => sub { return length($_[0]) >= 6; },
'max_length' => sub { return length($_[0]) <= 12; },
},
},
{ type => SCALAR, regex => qr/^\d+$/, optional => 1 },
);
print $name, '; $age ', (defined $age ? '' : 'not ' ), "defined.\n";
}
foo('yeehaw' ); #> yeehaw; age not defined
foo('yeehaw', 1); #> yeehaw; age defined
foo("yaaaaay", 'i'); # fails regex check
foo("short" ); # fails min_length check
foo("looooooooooong"); # fails max_length check
foo([]); # fails type check
foo(undef); # fails type check
use Params::Validate qw(:all);
sub foo {
#my $self = shift; # shift $self off first if OO
my %args = validate(@_, {
name => { type => SCALAR, regex => qr/^.{6,12}$/s },
age => { type => SCALAR, regex => qr/^\d+$/, optional => 1 },
});
print $args{name},
'; age ',
(defined $args{age} ? '' : 'not ' ),
"defined.\n";
}
foo( name => 'yeehaw' ); #> yeehaw; age not defined
foo( name => 'yeehaw' ); #> yeehaw; age not defined
# unrolls if passed a hashref
foo( { name => 'yeehaw', age => 1 } ); #> yeehaw; age defined
Contextual::Returnregex => qr/^\d+$/ - compare value against regular expressionisa => 'CGI::Application' - class validation; verify that the parameter is a class or subclass of the supplied arguement; can also be an arrayref of namescan => 'bar' - interface validation; verify that the parameter can perform a certain method; again, you can do an arrayref of method names@_untaint => 1 - for running in a tainted environment; untaint the data
optional => 1 - by default, each parameter is considered required; this makes them optional (when using positional validation, optional parameters must be after all required parameters)type => SCALAR | UNDEF is not the same as optional.undef, it will fail validation because the element was not found at all depends => [qw/other parameter names/] - dependanciesoptional => 1 but you wish it to become required if another optional parameter is entered, use thisvalidate (named parameters) you do this by providing a list of the names of the parameters it depends onvalidate_pos although there is a way to do it; possibly by the index of the required element
my %p =
validate_with
( params => \@_,
spec => { foo => { type => SCALAR },
bar => { default => 10 } },
allow_extra => 1,
called => 'The Quux::Baz class constructor',
);
my @p =
validate_with
( params => \@_,
spec => [ { type => SCALAR },
{ default => 10 } ],
allow_extra => 1,
called => 'The Quux::Baz class constructor',
);
Thank you.