Perl:如何获取按键排序的嵌套哈希值?

时间:2017-01-19 14:45:38

标签: perl sorting reference

我现在正在Perl中试验嵌套数据结构。假设我有哈希数组的哈希值,我想按字母顺序获取按键排序的值。我该怎么做?

代码:

#!/usr/bin/perl
use JSON::XS;
use Data::Dumper;
#use diagnostics;
use warnings;

my $school_data = {'School' => '156', 'Pupils' => [{'Person' => {name => 'Alice', age => 10, pet => 'cat'},'id' => 56},{'Person' => {name => 'John', age => 9, pet => 'dog'},id => 4}]};

print "\$school_data:" . Dumper ($school_data);

my $ref = $school_data->{Pupils};
foreach $pupil (@$ref){
    my @temp = sort (values $pupil->{'Person'});
    print "\n@temp\n";
}

给我一​​个输出:

    $school_data: $VAR1 = {
              'School' => '156',
              'Pupils' => [
                            {
                              'id' => 56,
                              'Person' => {
                                            'pet' => 'cat',
                                            'name' => 'Alice',
                                            'age' => 10
                                          }
                            },
                            {
                              'Person' => {
                                            'age' => 9,
                                            'name' => 'John',
                                            'pet' => 'dog'
                                          },
                              'id' => 4
                            }
                          ]
            };



10 Alice cat

9 John dog

我希望按字母顺序(宠物名称年龄)按键排序值:

cat Alice 10

dog John 9

期待您的帮助。谢谢。

1 个答案:

答案 0 :(得分:2)

哈希,因为我确定你知道,不要存储任何类型的订单,只需要键和值映射。

sort函数可以采用几乎任意的代码,返回位置相关的负数/ 0 /正数来定义排序顺序。

但是你需要对你的顶级排序'基于子键。

如果您需要按特定顺序输出值 - 请记住哈希是无序的,您可以使用slice

所以:

#!/usr/bin/env perl

use JSON::XS;
use Data::Dumper;

#use diagnostics;
use strict;
use warnings;

my @things = qw ( pet name age );

my $school_data = {
   'School' => '156',
   'Pupils' => [
      {  'Person' => { name => 'Alice', age => 10, pet => 'cat' },
         'id'     => 56
      },
      { 'Person' => { name => 'John', age => 9, pet => 'dog' }, id => 4 }
   ]
};

print "\$school_data:" . Dumper( $school_data->{Pupils} );

foreach my $pupil ( sort { $_ -> {Person} -> {name} 
                       cmp $_ -> {Person} -> {name} } 
                               @{ $school_data->{Pupils} } )
{
   print join " ", @{$pupil->{Person}}{@things}, "\n";
}

对于多键排序,排序工作正常 - 只要它返回的是一个数值。

所以你可以:

sort { $_ -> {Person} -> {name} cmp $_ -> {Person} -> {name}
    || $_ -> {Person} -> {age} <=> $_ -> {Person} -> {age}
    || $_ -> {Person} -> {pet} <=> $_ -> {Person} -> {pet} }