2014-03-06 61 views
0

我有一个键名数组,需要从散列中删除不在此列表中的任何键。Perl:删除散列中不存在的数组中的元素

我收集的哈希删除键是在遍历它是一件坏事,但它似乎工作:

use strict; 
use warnings; 
use Data::Dumper; 

my @array=('item1', 'item3'); 
my %hash=(item1 => 'test 1', item2 => 'test 2', items3 => 'test 3', item4 => 'test 4'); 

print(Dumper(\%hash)); 

foreach (keys %hash) 
{ 
    delete $hash{$_} unless $_ ~~ @array; 
}  

print(Dumper(\%hash)); 

给出了输出:

$VAR1 = { 
     'item3' => 'test 3', 
     'item1' => 'test 1', 
     'item2' => 'test 2', 
     'item4' => 'test 4' 
    }; 
$VAR1 = { 
     'item3' => 'test 3', 
     'item1' => 'test 1' 
    }; 

谁能给我解释一下这样做的更好/更清洁/更安全的方式?

非常感谢。

回答

1

不要使用smartmatch ~~,它基本上会被破坏,并且很可能在即将发布的Perl版本中被删除或大幅改变。

最简单的办法是建立一个新的哈希只包含那些你感兴趣的内容:

my %old_hash = (
    item1 => 'test 1', 
    item2 => 'test 2', 
    item3 => 'test 3', 
    item4 => 'test 4', 
); 
my @keys = qw/item1 item3/; 

my %new_hash; 
@new_hash{@keys} = @old_hash{@keys}; # this uses a "hash slice" 

如果要更新原有的哈希值,然后做%old_hash = %new_hash之后。如果你不希望使用另一个哈希,你可能想use List::MoreUtils qw/zip/

# Unfortunately, "zip" uses an idiotic "prototype", which we override 
# by calling it like "&zip(...)" 
%hash = &zip(\@keys, [@hash{@keys}]); 

具有同样的效果。

+0

非常感谢,这对我很好! –

+0

有没有办法做到这一点,没有临时哈希来保存片? –