I have to check hashrefs like this one
{ foo => 65, bar => 20, baz => 15 }
against an arrayref of hashrefs expressing conditions like this
[
{ foo => { "<=" => 75 } },
{ bar => { "==" => 20 } },
{ baz => { ">=" => 5 } },
]
and return a true value if all conditions are fulfilled.
Neither of the two data structures is pre-determined. One is built from parsing a string in a database, the other from parsing user input.
In the case above, I would return true, but if I checked the hashref against
[
{ foo => { "<=" => 60 } },
{ bar => { "==" => 20 } },
{ baz => { ">=" => 5 } },
]
I would return false, because foo in the first hashref is not <= 60.
The question is: what’s the best strategy for doing that?
I am thinking of
- building a series of subrefs via eval
- checking against the appropriate one among 5 different pre-built subrefs (one per case for >, <, <=, >= and ==)
Am I going down the wrong path altogether? and if not, what’s the best, eval or pre-built functions?
I have looked into Params::Validate but I am concerned that it’d be a lot of overhead, and I’d have to build the callbacks anyway.
Use code references instead, and you will have ready to go validators. I simplified your condition-structure. There is no need to have an extra array level in there, unless you have duplicate hash keys, which I assume you don’t.
The simplistic
sub { $_[0] <= 75 }will simply compare the first value of the arguments. By default, the last value evaluated in the subroutine will be its return value.Output: