如何删除哈希中不作为数组 (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'
    };

什么是更好/清洁/更安全的方法?

不要使用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}]);

具有相同的效果。

最新更新