【问题标题】:Perl: How do I get values of the nested hash sorted by the keys?Perl:如何获取按键排序的嵌套哈希值?
【发布时间】:2017-01-19 14:45:37
【问题描述】:

这些天我在 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

期待您的帮助。谢谢。

【问题讨论】:

标签: perl sorting reference


【解决方案1】:

我相信你知道哈希,不存储任何排序,只存储键和值映射。

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} } 

【讨论】:

  • 不知道我可以使用带散列的切片。非常感谢!
猜你喜欢
  • 2014-10-17
  • 2018-07-21
  • 2018-12-17
  • 2010-10-20
  • 1970-01-01
  • 2012-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多