我在完成一个简单任务时遇到问题。我有以下散列哈希:
%hash = (
personA => {
2017 => 1,
2018 => 2,
},
personB => {
2015 => 4,
2013 => 28,
2014 => 1, .
},
personC => {
2013 => 3,
2011 => 2,
2012 => 45,
},
);
我正在尝试为每个人打印最早的年份,例如类似于:
personA 2017
personB 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}};
通过人民。然后,取消引用每个人的哈希以获取年份列表:
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
您可以在保持简单性的同时完全避免使用任何模块。
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]-按升序对键进行排序(默认情况下),然后获得第一个键。