如何在Perl中存储数组或散列中的重复值?

时间:2008-10-31 22:16:09

标签: perl arrays hash duplicates

让我们轻松一点。我想要的是什么:

@array = qw/one two one/;
my @duplicates = duplicate(@array);
print "@duplicates"; # This should now print 'one'.

如何打印数组/哈希的重复值?

6 个答案:

答案 0 :(得分:8)

sub duplicate {
    my @args = @_;
    my %items;
    for my $element(@args) {
        $items{$element}++;
    }
    return grep {$items{$_} > 1} keys %items;
}

答案 1 :(得分:2)

您想要做的额外详细,额外可读的版本:


sub duplicate {
   my %value_hash;
   foreach my $val (@_) {
     $value_hash{$val} +=1;
   }
   my @arr;
   while (my ($val, $num) = each(%value_hash)) {
     if ($num > 1) {
        push(@arr, $val)
     }
   }
  return @arr;
}

这可以大大缩短,但我故意将它留下冗长,以便你可以跟进。

但是,我没有测试它,所以请注意我的错别字。

答案 2 :(得分:2)

# assumes inputs can be hash keys
@a = (1, 2, 3, 3, 4, 4, 5);

# keep count for each unique input
%h = ();
map { $h{$_}++  } @a;

# duplicate inputs have count > 1
@dupes = grep { $h{$_} > 1 } keys %h;

# should print 3, 4
print join(", ", sort @dupes), "\n";

答案 3 :(得分:0)

使用字典,将值放入键中,将计数值放入值中。

啊,刚刚注意到你已被标记为perl

while ([...]) {
 $hash{[dbvalue]}++
}

答案 4 :(得分:0)

问题中未指明的是应该返回重复项的顺序。

我可以想到几种可能性:不在乎;按输入列表中第一个/第二个/最后一个出现的顺序;排序

答案 5 :(得分:-1)

我要去打高尔夫球了!

sub duplicate {
    my %count;
    grep $count{$_}++, @_;
}

@array = qw/one two one/;
my @duplicates = duplicate(@array);
print "@duplicates"; # This should now print 'one'.

# or if returning *exactly* 1 occurrence of each duplicated item is important
sub duplicate {
    my %count;
    grep ++$count{$_} == 2, @_;
}