如何在散列中查找每个键的最小值和最大值

时间:2014-02-14 09:30:40

标签: perl hash

我想获得每个密钥的最小值和最大值:

DATA:
$VAR1 = { '0.0' => {  
                    '0.0',
                    '1.2',
                    '2.0',
                    '0.4',
                   },
          '0.2' => {
                    '2.3',
                    '0.1',
                    '0.0',
                   }
        };

我的代码段:

use List::MoreUtils qw( minmax );

for my $key (sort {$a <=> $b} keys (%seedhash))
{
    my ($min, $max) = minmax values %{$seedhash{$key}};
    print "$key {";
    for my $values (sort {$a <=> $b} keys %{$seedhash{$key}})
    {
        print "$values, ";
    }
    print "} $min : $max \n";
} 

我想要的输出是

0.0 {0.0, 1.2, 2,0, 0.4, } 0.0 : 2.0
0.2 {0.0, 0.1, 2.3, } 0.0 : 2.3

但是我的输出是这样的:

0.0 {0.0, 1.2, 2,0, 0.4, }  HASH(0x13d13ec0) : HASH(0x142dad70)
0.2 {0.0, 0.1, 2.3, } HASH(0x137e7810) : HASH(0x142fef10)

我不确定我的语法是否正确。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

my %seedhash = ( '0.0' => [
                    '0.0',
                    '1.2',
                    '2.0',
                    '0.4',
                   ],
          '0.2' => [
                    '2.3',
                    '0.1',
                    '0.0',
                   ]
);

use List::MoreUtils qw( minmax );

for my $key (sort {$a <=> $b} keys %seedhash)
{
    my ($min, $max) = minmax @{$seedhash{$key}};
    print "$key {";
    for my $values (sort {$a <=> $b} @{$seedhash{$key}})
    {
        print "$values, ";
    }
    print "} $min : $max \n";
}

输出

0.0 {0.0, 0.4, 1.2, 2.0, } 0.0 : 2.0
0.2 {0.0, 0.1, 2.3, } 0.0 : 2.3