在perl中过滤哈希散列 [英] Filtering a hash of hash in perl
问题描述
我有一个哈希散列,我需要过滤。我确实发现了如何做查找,但没有回答我的问题。
I have a hash of hash that I need to filter. I did find how to do a lookup but it did not answer my question.
假设我有这样的哈希散列:
Say I have a hash of hash like that :
my %HoH = (
flintstones => {
husband => "fred",
pal => "barney",
town => "springfield"
},
jetsons => {
husband => "george",
wife => "jane",
"his boy" => "elroy",
},
simpsons => {
husband => "homer",
wife => "marge",
kid => "bart",
town => "springfield",
},
);
我可以说我想要来自Springfield的所有城镇。
I lets say I want all the townfolks from springfield. I want the same hash of hash in output without the outsiders.
my %HoH = (
flintstones => {
husband => "fred",
pal => "barney",
town => "springfield"
},
simpsons => {
husband => "homer",
wife => "marge",
kid => "bart",
town => "springfield",
},
);
这似乎很愚蠢,但无法弄清楚如何过滤结构。我们的目标是在筛选后迭代Springfield的所有人。
It seems silly but can't figure out how to filter the struture. The goal would be to iterate on all the people of springfield after filtering.
我当然做了一些研究,最接近的是哈希切片。
但它们看起来很可怕。
I of course did some research and the closest thing I came by is hash slices. But they seem scary.
推荐答案
首先需要找到要移除的元素的键: / p>
You first need to find the keys of the elements you want to remove:
grep { $HoH{$_}{town} eq 'springfield' } keys(%HoH)
然后删除它们:
Then you delete them:
delete $HoH{$_} for grep { $HoH{$_}{town} eq 'springfield' } keys(%HoH);
或者使用散列片:
Or using a hash slice:
delete @HoH{ grep { $HoH{$_}{town} eq 'springfield' } keys(%HoH) };
这篇关于在perl中过滤哈希散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!