Perl:在散列数组中找到最大值和最小值

Luk*_*uke 1 arrays sorting perl hash

我在Perl中有以下结构:

#!/usr/bin/perl
use strict;
use warnings;

my %hash = (
    'firstitem' => {
        '1' => ["A","99"],
        '2' => ["B","88"],
        '3' => ["C","77"],
    },
    'seconditem' => {
        '3' => ["C","100"],
        '4' => ["D","200"],
        '5' => ["E","300"],
    },
);
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种方法来找到每个哈希数组中的最大数量和最小数量.所以输出将是

firstitem: max:99, min:77
seconditem: max:300, min:100
Run Code Online (Sandbox Code Playgroud)

我的想法是先对二级密钥进行排序,然后在for循环中进行冒泡排序或其他排序.它看起来不是很优雅和聪明.

    foreach my $k1 (keys %hash) {
        my $second_hash_ref = $hash{$k1};                   
        my @sorted_k2 = sort { $a <=> $b } keys %{$second_hash_ref}; 
        foreach my $i (0..$#sorted_k3){ 
            #bubble sort or other sort
        }
    }
Run Code Online (Sandbox Code Playgroud)

Mat*_*cob 5

List :: Util是一个提供minmax功能的核心模块:

use strict;
use warnings;

use List::Util qw(min max);

my %hash = (
    'firstitem' => {
        '1' => ["A","99"],
        '2' => ["B","88"],
        '3' => ["C","77"],
    },
    'seconditem' => {
        '3' => ["C","100"],
        '4' => ["D","200"],
        '5' => ["E","300"],
    },
);

for my $key (keys(%hash)) {
    my @numbers = map { $_->[1] } values(%{$hash{$key}});
    printf("%s: max: %d, min: %d\n", $key, max(@numbers), min(@numbers));
}
Run Code Online (Sandbox Code Playgroud)

输出:

firstitem: max: 99, min: 77
seconditem: max: 300, min: 100
Run Code Online (Sandbox Code Playgroud)