按子节点分组Perl对象

时间:2013-07-25 18:08:46

标签: perl sorting object

我有一个如下所示格式的对象,我需要按可用月份对它们进行分组。 1000,2000等。是美元金额,下一级是(6,4)是月。

我的对象:

$VAR1 = {
          '1000' => {
                      '6' => {
                               'APR' => '13.9'
                             },
                      '4' => {
                               'APR' => '11.9'
                             }
                    },
          '2000' => {
                      '6' => {
                               'APR' => '13.9'
                             },
                      '4' => {
                               'APR' => '11.9'
                             }
                    },
          '4000' => {
                      '6' => {
                               'APR' => '13.9'
                             },
                      '4' => {
                               'APR' => '11.9'
                             }
                    }
          '5000' => {
                      '6' => {
                               'APR' => '13.9'
                             }
                    }
        };

我想要的对象:

$VAR1 = {
    '6' => {
             '1000',
             '2000',
             '4000',
             '5000'
           },
    '4' => {
             '1000',
             '2000',
             '4000'
           }
}

1 个答案:

答案 0 :(得分:2)

my %new_hash;
for my $amount (sort { $a <=> $b } keys(%$VAR1)) {
   for my $month (keys(%{ $VAR1->{$amount} })) {
      push @{ $new_hash{$month} }, $amount;
   }
}