我有一个看起来像这样的哈希:
my $hash = {
level1_f1 => {
level2_f1 => 'something',
level2_f2 => 'another thing'
},
level1_f2 => {
level2_f3 => 'yet another thing',
level2_f4 => 'bla bla'
level2_f5 => ''
}
...
}
Run Code Online (Sandbox Code Playgroud)
我还得到了一个对应于“level2”键的值列表,我想知道你是否存在于散列中。
@list = ("level2_f2", "level2_f4", "level2_f99")
我不知道@list 的每个元素属于哪个“level1”键。我认为找到它们是否存在的唯一方法是使用 foreach 循环遍历 @list,另一个 foreach 循环遍历 %hash 的键并检查
foreach my $i (@array) {
foreach my $k (keys %hash) {
if (exists $hash{$k}{$list[$i]})
}
}
Run Code Online (Sandbox Code Playgroud)
但我想知道是否有更有效或更优雅的方法来做到这一点。我找到的所有答案都要求您知道“level1”键,而我不知道。
谢谢!!
使用值:
for my $inner_hash (values %$hash) {
say grep exists $inner_hash->{$_}, @list;
}
Run Code Online (Sandbox Code Playgroud)