I wanted to build an awesome place for people to discuss module specific issues, but I don't have any more time for this, and there are much better places to discuss Perl-related issues. I'd recommend asking your question on Stack Overflow or on Perl Monks.
If you are looking for a Perl tutorial or Perl-related news, I hope these links will serve you well.
Posted on 2008-03-03 22:10:55-08 by fergal in response to 7254
Re: Defining optional hash keys

At the moment there is no builtin way to do this but you can make a way to do it and you can even make it convenient (if slightly inefficient).

sub opthash { my ($must_have, $can_have) = @_; # combine the mandatory and optional fields to make a new hash with all of them together my %upper_limit = %$must_have, %$can_have; return all(superhash($must_have), subhash($upper_limit)) } $data_expect = opthash( { name => 'tester', data => ignore(), records => 0 }, { husband => 'joey', } }

The superhash will ensure that all of the mandatory fields exist. The subhash allows the optional fields to be missing but if they are present they must match the spec.

It's a bit inefficient because you end up checking all the mandatory fields twice but that's not such a big deal (particularly as Test::Deep caches comparison results during a run of is_deeply).

If you want you can also use code() which allows you to have data passed to a function for comaparison but that looses diagnostic info.

I think it's really time for me to write a doc on how to extend Test::Deep with home-made comparators. The API has been stable for years now.

Hope that helps. If I had time, I think I would alter Test::Deep::Hash to allow optional keys, then provide a function in Test::Deep to give an interface to this. If you feel like digging in, I'm happy to review and apply patches.

Direct Responses: 7275 | Write a response