PrePAN

Sign in to PrePAN

Params::Validate::Array Provides an alternative version of Params::Validate::validate() which returns args as an list, not a hash

Author
sambrain@github
Date
URL
Status
In Review
Good

Synopsis

use Params::Validate::Array qw(SCALAR ARRAYREF validate ...);

sub foo1 {
  my ($a, $b, $c) = validate( @_,
            # note the arrayref, not a hashref as in Params::Validate
            [ a => 1,   #   types of a, b, & c are 
              b => 0,   #+ unspecified. a is mandatory,
              c => 0,   #+ b & c optional
            ]
  );
  print "a = $a\n";
  print "b = ", $b // "undefined", "\n";
  print "c = ", $c // "undefined", "\n";
}

# calling:
  foo1(a => 'hello', c => 'there');
# prints:
#   a = hello
#   b = undefined
#   c = there

# calling:
  foo1(b => 1, c => 'foo');
# PV throws error:
#   "Mandatory parameter 'a' missing in call to main::foo1..."

sub foo2 {
  my ($x, $y) = validate( @_,
        # again, arrayref
        [ x => {type => HASHREF, optional => 1},  #  hashref 'x' is optional,
          y => {type => SCALAR                         },  #+ scalar 'y' mandatory
        ]
   );
 }

# when used with hashref descriptor, acts like Params::Validate::validate()
sub foo3 {
    my %arg = validate( @_,
              # Note hashref
              { x => {type => HASHREF, optional => 1}, 
                y => {type => SCALAR                },
              }
    );
}

Description

Yet Another Params::Validate::XXX module.

I like my validate() to return args as a list instead of a hash, and without having to resort to the more complicated call of P::V::validate_with()

This module changes only the behaviour of P::V::validate() and only when the descriptor is an arrayref (as it has to be to preserve the order of the args). If P::V::A::validate() is called with a hashref descriptor, it reverts to P::V::validate()'s behaviour.

All other PVA routines are simple pass-throughs to P::V (except for P::V::A::validation_options() which might increment a stack_skip => ... arg to hide the extra layer of call stack). P::V::A::validate() is a relatively simple wrapper around P::V::validate().

Comments

To be pedantic, it returns args as a list, not an array ;-)

Just to clarify, in foo1(), $a, $b and $c are only positional within the function, not when it's called?
Yes, mjemmeson@, I tend to be a bit loose with my use of "list" vs "array" language.

Also, I had a *major* typo in foo1() above. The line:
c => 1) #+ b & c optional
should have read:
c => 1, #+ b & c optional
(*Embarrasment*) Sorry 'bout that. Let me correct that and add some typical usage code for illustration (and I'll also add that to the P::V::A POD)

Thanks for your input. I appreciate your taking the time.

Please sign up to post a review.