Niche Modules - Data::FetchPath

Ovid on 2009-05-19T21:28:11

Some modules will have very little take-up, but when you need them, you need them. Hence, my Data::FetchPath, which should be on a mirror near you soon.

For a whole variety of reasons I sometimes find I need to know where in a data structure a particular piece of data is. I've used it for Prolog-style data unification and changing data structures on the fly, but I also sometimes use it for digging into complex objects and I want to know which path in a DBIx::Class resultsource holds a given value.

use Data::FetchPath 'path';

# find all http:// https:// urls
my $paths = path($complex_data_structure, qr{^https?://});
foreach my $path (@$paths) {
    print eval "\$complex_data_structure->$path\n";
}

The data structure only supports array and hashrefs and the value you match against must be a scalar or a regex. Though as I was trying to explain this to my brother, I realized that I should add support for callbacks. For example, if you wanted to know how many values in an array of arrays are prime:

print scalar @{ path($AoA, sub { is_prime(shift) }) };

Callbacks should be trivial to add, but I need to get some sleep.

And yes, it handles circular data structures. That was my first bug with it. It's a bit hackish, but it does the job.

As is usually the case with most of my new code, you can get it from github.


Smartmatch?

zby on 2009-05-20T09:10:25

I have just discovered that smartmatch provides great semantics for testing for true with dynamic checks. It implements scalar, regexes and callbacks and also arrays and hashes. It gives the check creator full flexibillity - while not requiring complex checks (or rather shifting the check complexity to the core language).

Of course 5.10 is still rare in production - so in FormHandler we just emulate smartmatch.

Re:Smartmatch?

Ovid on 2009-05-20T09:18:01

We're not on 5.10 at work and probably won't be any time soon. Still, while smart match is a great "first check", does it return the paths? That's what I need, not just the values.