Perl:根据它们的值删除散列中的元素

Perl: Delete element in hash based on their values

我有一个散列,想删除一些元素(元素=键+值)。 key删除一个元素很简单,但是如果删除的条件是根据值,我不知道怎么办。

my %h = (  'a' => 1
         , 'b' => 1
         , 'c' => 2
       );

# delete by key
delete $h{'c'};

print map { "$_ $h{$_}\n" } keys %h;
# a 1
# b 1

我想使用值删除:

delete %h value >1

您可以高效地遍历具有 eachdelete 匹配项的条目:

#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;

my %h = (
    'a' => 1,
    'b' => 1,
    'c' => 2
    );

while (my ($k, $v) = each %h) {
    delete $h{$k} if $v > 1;
}

print Dumper(\%h);

来自 the each documentation(已强调):

Any insertion into the hash may change the order, as will any deletion, with the exception that the most recent key returned by each or keys may be deleted without changing the order.

这意味着上面的循环可以安全地查看散列的每个元素并删除所有符合条件的元素。


您也可以使用 slice 一次删除多个条目。只需要建立一个要删除的键列表,例如通过过滤 keys:

的结果
delete @h{grep { $h{$_} > 1 } keys %h};