我有一个键名称数组,需要从哈希中删除不在此列表中的任何键。
我发现在迭代哈希时删除哈希中的键是一件坏事,但它似乎确实有效:
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'
};
更好/更清洁/更安全的方法是什么?
最佳答案
不要使用 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
。如果您不想使用其他哈希,您可能需要使用 List::MoreUtils qw/zip/
:
# Unfortunately, "zip" uses an idiotic "prototype", which we override
# by calling it like "&zip(...)"
%hash = &zip(\@keys, [@hash{@keys}]);
具有相同的效果。
关于arrays - 如何删除散列中不作为数组(Perl)中的元素存在的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22222495/