arrays - 如何删除散列中不作为数组(Perl)中的元素存在的键?

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

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

最佳答案

不要使用 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/

相关文章:

python - 为文件系统上的每个文件创建哈希

ruby - RSpec:在 RSpec 中测试大型哈希

c# - 在 C# 和 SQL Server 2008 R2 中使用 MD5

javascript - 如何从2个数组中获取总最小值和最大值

arrays - Swift数组元素地址

javascript - js 每个循环都会向对象或数组添加一个深度

perl - Perl不会进入错误部分

perl - 在 Perl 中我应该使用什么来代替 printf ?

java - 当到达最后一个文本时重复数组?

perl - 为什么这个 Perl 代码在 shell 中运行,而不是在脚本中运行?