我是Perl的新手(并且是一般编程人员),并且在完成一个简单任务时遇到问题。我有以下散列哈希:
%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}};
感谢帮助。
答案 0 :(得分: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
答案 1 :(得分: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] -按升序对键进行排序(默认情况下),然后获得第一个键。