[ABE.pm] patting my younger self on the back: Number::Tolerant

Ricardo SIGNES perl.abe at rjbs.manxome.org
Wed Jul 30 07:02:21 PDT 2008


First off: Tom, if you upgrade Number::Tolerant without testing, things might
break.

Okay, now:

I'm working on doing some generic data validation work.  To greatly simplify,
I'm writing a schema language to describe the common data types found in
JavaScript, Perl, PHP, Python, Ruby, and so on.  I'm going to use it mostly to
validate JSON and YAML encoded data.

Simplified, some entries can contain things like this:

  array: size: { min: 10, max: 20 }

  num: range: { min-ex: 0, max: 1 }

So I needed a way to convert these ranges into validators (here, closures) that
would do the validation.  It started out as lame but easy when I only had "min"
and "max" but when I needed exclusive endpoints (in the second example, 0 is
not okay, but 0.000000000000000000000000001 is) it got really obnoxious and
tedious.

Then I realized that this was solved!  I used Number::Tolerant, made a bunch of
ranges like (x >= 10, x <= 20) or (x > 0, x <=1) and fed them to
List::Util::reduce to find their total intersection.  Anything in that
intersecting range was a valid number.

Nice!

-- 
rjbs


More information about the ABE-pm mailing list