I have downloaded a complex JSON data structure from https://api.ncbi.nlm.nih.gov/variation/v0/beta/refsnp/8127500
it is so large, I cannot search it easily.
I have tried Data::Search, but it does not return what I need.
How can I search a data structure/hash, e.g. the minimal working example,
my %d = (
a => {
b => 1
}
);
search for the key 1
and return {a}{b}
?
CodePudding user response:
#! /usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
sub walk { _walk(@_, []) }
sub _walk {
my ($value, $s, $path) = (@_);
my @r;
if (ref $s) {
if (ref [] eq ref $s) {
for my $i (0 .. $#$s) {
my $p = walk($value, $s->[$i], [@$path, $i]);
push @r, @$p if $p;
}
} elsif (ref {} eq ref $s) {
for my $k (keys %$s) {
my $p = walk($value, $s->{$k}, [@$path, $k]);
push @r, @$p if $p;
}
}
return \@r
} else {
return [$path] if $s == $value;
}
}
my %d = (a => {b => [0, 1, 2]},
c => [0, 1, [{d => 2, e => 3}]]);
my $paths = walk(2, \%d, []);
say "@$_" for @$paths;