Perl:删除散列中不存在作为数组元素的键

时间:2014-03-06 11:01:37

标签: arrays perl hash key

我有一组键名,需要从哈希中删除不在此列表中的任何键。

我收集哈希中的删除键是一件坏事,同时迭代它,但它似乎确实有效:

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'
    };

有人可以向我解释更好/更清洁/更安全的方法吗?

非常感谢。

2 个答案:

答案 0 :(得分:3)

请勿使用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}]);

具有相同的效果。

答案 1 :(得分:0)

%hash = %hash{@array}

https://perldoc.perl.org/perldata.html

perldoc

  

正文必须至少包含30个字符;您输入了21。   无法提交您的答案。请参阅上面的错误。