in reply to Recursive data structure munging - arrayrefs to hashrefs
First, the data structure you've shown isn't actually valid: $foo = { [ ... ] }; is missing a hash key, so for now I'm just going to assume $foo = { foo => [ ... ] };
I need to create a path-type lookup
You may be interested in Data::Diver. I also showed some custom "diver" type code here and here.
Also, it's unclear to me if your data structure always alternates between array and hash refs? Or can you ever have a hash of hashes? If not, this code will work on the sample data you showed, but it does make some assumptions about the structure of the input data. If you need to differentiate between arrays and hashrefs, you'll have to add things like if (ref $e eq 'ARRAY') { ... } elsif (ref $e eq 'HASH') { ... }.
sub rekey { my $h = shift; for my $k (keys %$h) { next unless ref $$h{$k}; my %n; for my $e (@{$$h{$k}}) { die "duplicate key '$$e{name}'" if exists $n{$$e{name}}; $n{$$e{name}} = $e; rekey($e); } $$h{$k} = \%n; } } rekey( $foo );
Update: You might also want to take a look at Data::DPath or Data::Path, I haven't used these myself but they sound like they might be fitting.
Update 2: Fixed typo in text.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Recursive data structure munging - arrayrefs to hashrefs
by flightdm (Acolyte) on Aug 31, 2017 at 20:01 UTC | |
by haukex (Archbishop) on Aug 31, 2017 at 20:30 UTC |