在perl中找到重复的哈希键并在它们中找到最大值

时间:2012-09-28 12:04:54

标签: perl hash key duplicates

我的数据基本上是一个文件:

a
2
b
6
a
4
f
2
b
1
a
7

我有这个哈希:

%hash = {
    a => 2,
    b => 6,
    a => 4,
    f => 2,
    b => 1, 
    a => 7,
};

如何找到重复的密钥?我想要一个具有最大价值的那个。

期望的输出:

a-->7 
b-->6
f-->2

2 个答案:

答案 0 :(得分:3)

如果您只想要特定键的最高值,则将逻辑添加到哈希的赋值中。在您添加键和值时,请执行以下操作:

unless (exists $hash{$key} and $hash{$key} >= $value)
{
   $hash{$key} = $value;
}

如果需要保留所有值,则将每个键指向一个值数组。以下是您的作业:

#Add an element to the array of values for this key.
push @{ $hash{$key} }, $value;

这是在给定键的结果数组中找到最大值的好方法:

use List::Util qw/max/;

print max @{ $hash{$key} };

答案 1 :(得分:0)

所以任务是逐行读取这些行。使用第一个作为键,第二个作为值,您必须跟踪每个键的最大值。

%info;

# A loop reading two lines.
while( my $key = <> ) {
    my $value = <>;

    # Handle the case where there are an odd number of lines.
    die "Odd number of lines" unless (defined $value);

    # Assuming only non-negative values, we just silently want to compare
    # keys not seen before as having value 0. See 'perllexwarn' manual page
    no warnings 'uninitialized'; 

    $info{$key} = $value if $info{$key} <= $value;
}

# Dump the result
say "$_ --> $info{$_} for keys %info;

但与往常一样,有不止一种方法可以做到这一点。特别是一次读取两行。此外,有些人可能更愿意明确测试$info{$key}是否已经存在,而不仅仅是沉默警告。