多维散列排序 - Perl [英] Multi dimensional hash sort - Perl

查看:63
本文介绍了多维散列排序 - Perl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的需要一些帮助来理解这个散列并使用排序来处理它.

I really need some help in understanding this hash and processing it with sort.

这里是哈希:

$VAR1 = {

    Key1:Key1_si => {

        'KeyA' => {
            Keya => 'abcd, defg',
            keyb => '1000',
            keyc =>  '80%',
            keyd =>  '2011.10.09',
            keye => '1234-UR-DDDD',
            keyf => 'rwh',
            keyg => '600',
            keyh => 'red',
            keyi => '900',
            keyj => '',
            keyk =>'int4678_tt',
        },

        'KeyB' => {

            Keya => 'abcd, defg',
            keyb => '2000',
            keyc =>  '100%',
            keyd =>  '2011.11.09',
            keye => '1234-UR-DDDD',
            keyf => 'rwh',
            keyg => '500',
            keyh => 'red',
            keyi => '400',
            keyj => '',
            keyk =>'int4678_tt',
        },
    },

};

问题:我想根据其值不同的keyc"对这个散列进行排序.所以,我想根据如下所示进行排序:

Question: I want to sort this hash on the basis of 'keyc' whose value is varied. So, I want to sort on the basis like below:

Key1:Key1_si->KeyB->Keyc

Key1:Key1_si->KeyA->keyc

此外,我希望输出带有排序值以及其他属性,例如:

Also, I want to have the output with the sorted values along with the rest of attributes like :

打印:

Key1:Key1_si KeyB Keya keyd Keyc keyf

Key1:Key1_si KeyA keya keyd Keyc keyf

有人可以帮助我使用 perl 中的代码来执行上面提到的排序.我将非常感谢您的时间和努力.

Can somebody please help me with the code in perl to perform sort as mentioned above. I will really appreciate your time and efforts.

推荐答案

您想对密钥对列表进行排序,因此必须从构建密钥对列表开始.对数组的引用是显而易见的答案.一旦你想通了这一点,一切就顺理成章了.

You want to sort a list of key pairs, so you have to start by building a list of key pairs. A reference to an array is the obvious answer. Once you've figured this out, everything is straight forward.

构建密钥列表:

my @unsorted_keys;
for my $k1 (keys(%$VAR1)) {
   for my $k2 (keys(%{ $VAR1->{$k1} })) {
      push @unsorted_keys, [ $k1, $k2 ];
   }
}

对这些键进行排序:

my @sorted_keys = sort {
   my ($a_k1, $a_k2) = @$a;
   my ($b_k1, $b_k2) = @$b;

   ( my $a_pc = $VAR1->{$a_k1}{$a_k2}{keyc} ) =~ s/%//;
   ( my $b_pc = $VAR1->{$b_k1}{$b_k2}{keyc} ) =~ s/%//;

   $a_pc <=> $b_pc
} @unsorted_keys;

迭代已排序的键:

for (@sorted_keys) {
   my ($k1, $k2) = @$_;
   my $hash = $VAR1->{$k1}{$k2};
   ... do stuff with %$hash ...
}

这篇关于多维散列排序 - Perl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆