如何搜索大型数据结构和 return 给出特定值的 keys/arrays 系列?
How to search a large data structure and return the series of keys/arrays that gives a particular value?
我从 https://api.ncbi.nlm.nih.gov/variation/v0/beta/refsnp/8127500
下载了一个复杂的 JSON 数据结构
太大了,不好找。
我试过Data::Search,但return不是我需要的。
如何搜索数据 structure/hash,例如最小的工作示例,
my %d = (
a => {
b => 1
}
);
搜索键 1
和 return {a}{b}
?
#! /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;
我从 https://api.ncbi.nlm.nih.gov/variation/v0/beta/refsnp/8127500
下载了一个复杂的 JSON 数据结构太大了,不好找。
我试过Data::Search,但return不是我需要的。
如何搜索数据 structure/hash,例如最小的工作示例,
my %d = (
a => {
b => 1
}
);
搜索键 1
和 return {a}{b}
?
#! /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;