[英]How can I delete keys in hash that don't exist as elements in array (Perl)?
I have an array of key names and need to remove any keys that are not in this list from a hash.我有一个键名数组,需要从哈希中删除不在此列表中的任何键。
I gather deleting keys in a hash is a Bad Thing while iterating over it, but it does seem to work:我在迭代时收集散列中的删除键是一件坏事,但它似乎确实有效:
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));
gives the output:给出输出:
$VAR1 = {
'item3' => 'test 3',
'item1' => 'test 1',
'item2' => 'test 2',
'item4' => 'test 4'
};
$VAR1 = {
'item3' => 'test 3',
'item1' => 'test 1'
};
What is a better/cleaner/safer way of doing this?这样做的更好/更清洁/更安全的方法是什么?
Don't use smartmatch ~~
, it's fundamentally broken and will likely be removed or substantially changed in upcoming releases of Perl.不要使用 smartmatch
~~
,它从根本上被破坏了,可能会在即将发布的 Perl 版本中被删除或大幅更改。
The easiest solution is to build a new hash only containing those elements you're interested in:最简单的解决方案是构建一个仅包含您感兴趣的元素的新哈希:
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"
If you want to update the original hash, then do %old_hash = %new_hash
afterwards.如果要更新原始散列,请在之后执行
%old_hash = %new_hash
。 If you don't want to use another hash, you might like to use List::MoreUtils qw/zip/
:如果您不想使用其他哈希,您可能想
use List::MoreUtils qw/zip/
:
# Unfortunately, "zip" uses an idiotic "prototype", which we override
# by calling it like "&zip(...)"
%hash = &zip(\@keys, [@hash{@keys}]);
which has the same effect.具有相同的效果。
%hash = %hash{@array}
https://perldoc.perl.org/perldata.html https://perldoc.perl.org/perldata.html
Body must be at least 30 characters;
正文必须至少为 30 个字符; you entered 21. Your answer couldn't be submitted.
您输入了 21。您的答案无法提交。 Please see the error above.
请参阅上面的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.