在哈希散列中打印最低值(perl)

问题描述 投票:2回答:2

我是Perl的新手(以及一般的编程),我遇到了完成一项简单任务的问题。我有以下哈希散列:

%hash = (
personA => {
    2017   => 1,
    2018   => 2,
},
personB => {
    2015   => 4,
    2013   => 28,
    2014   => 1, .
},
personC => {
    2013   => 3,
    2011   => 2,
    2012   => 45,
},
);

我试图为每个人打印出最早的一年,例如就像是:

personA 2017

人2013

personC 2011

似乎List :: Util是最好的工具,但我找不到适应我的数据的例子。我遇到了麻烦,因为我找到的解决方案是尝试排序/打印哈希的第一级(即personA等),而不是多年。

use strict;
use warnings;

my %hash;
my $hash; 

%hash = (
personA => {
    2017   => 1,
    2018   => 2,
},
personB => {
    2015   => 4,
    2013   => 28,
    2014   => 1,
},
personC => {
    2013   => 3,
    2011   => 2,
    2012   => 45,
},
);

use List::Util qw(min);
my $min = min keys %hash;
$hash = {$min => $hash->{$min}};

感谢帮助。

perl hash
2个回答
3
投票

循环通过人民。然后,取消引用每个人哈希以获取年份列表:

use warnings;
use strict;
use List::Util qw(min);

my %people = (
personA => {
    2017   => 1,
    2018   => 2,
},
personB => {
    2015   => 4,
    2013   => 28,
    2014   => 1,
},
personC => {
    2013   => 3,
    2011   => 2,
    2012   => 45,
},
);

for my $person (sort keys %people) {
    my $min = min(keys %{ $people{$person} });
    print "$person $min\n";
}

输出:

personA 2017
personB 2013
personC 2011

2
投票

您可以在保持简洁的同时避免使用任何模块。

use warnings;
use strict;

my %hash = (
    personA => {
        2017 => 1,
        2018 => 2,
    },
    personB => {
        2015 => 4,
        2013 => 28,
        2014 => 1,
    },
    personC => {
        2013 => 3,
        2011 => 2,
        2012 => 45,
    },
);

foreach my $person ( sort keys %hash ) {
    printf( "%s %d\n", $person, ( sort keys %{ $hash{$person} } )[0] );
}

(排序键%{$ hash {$ person}})[0] - 按升序排序键(默认情况下),然后获取第一个键。

© www.soinside.com 2019 - 2024. All rights reserved.