Getting started with Params::Validate

So I have a module that exports some functions that each take a single hashref as an argument, and I want to be sure that:

  1. I really have got a single hashref
  2. The contents of the hashref conform to my specification

I'd never used Params::Validate before now, so this looked like an ideal opportunity.

Here's what I came up with:

sub _validate_me {

# Raise exception if we don't have exactly one hashref
validate_pos( @_
, sub { TYPE => HASHREF } );

# P::V only tests lists.
my(@test) = %{$_[0]};

# Now we have our validation specs for the hashref. We accept :
# keys foo,bar and baz, each with defined scalar values of length > 1
# keys qux and tla with defined scalars as values.
# Anything else is a fatal error.
validate( @test
, { foo => { type => SCALAR
, callbacks =>
{ 'foo set' => sub { length($_[0])>1 } } }
, bar => { type => SCALAR
, callbacks =>
{ 'bar set' => sub { length($_[0])>1 } } }
, baz => { type => SCALAR
, callbacks =>
{ 'baz set' => sub { length($_[0])>1 } } }
, qux => { type => SCALAR }
, tla => { type => SCALAR } } );
}

And in the calling code :

sub do_stuff {
_validate_me(@_);
# Invalid? BOOM
my($args) = shift;

#Continue processing.
#..
}

We could obviously push quite a lot of validation logic into the callbacks, which has the benefit of making the actual application code much cleaner.

Leave a comment

About Stephen Cardie

user-pic I blog about Perl.