-1

I have a hash like this:

{ ABC => [1, 2],
     1 => [11, 12,13,14],
     13 => [17,20] }

I want to generate a hash of hashes like this:

(ABC => { 1 => {11 => {},
                12 => {},
                13 => { 17 => {}
                        20 = {} },
                14 => {}
               },
          2 => {}
        }

)

The above hash is nothing but a tree with a root node and further child nodes.

I understand we have to use recursion to check child nodes for every parent node. I have looked at the question previously asked here. I am unable to understand how during recursion specific node's data is stored under its particular parent key. In other words how can hash of hashes be populated recursively ?

Appreciate any pointers or explanation.

Thanks for your time

4

3 回答 3

3

真正的问题是你并不真正知道你想要什么。

 {ABC => 1 => 11 => {}
     => 1 => 12 => {}
     => 1 => 13 => 17 => {}
                => 20 = {}
     => 1 => 14 => {}
} 

只是一种非常奇怪的写作方式

{
   ABC => "1",
   11  => {},
   1   => "12",
   {}  => "1",
   13  => "17",
   {}  => "20",
   {}  => "1",
   14  => {},
}

这是没有意义的。我想你实际上想要

{
   ABC => {
      1 => {
         11 => {},
         12 => {},
         13 => {
            17 => {},
            20 => {},
         },
         14 => {},
      },
   },
}

既然您知道自己想要什么,就应该尝试实施它。

于 2012-08-07T19:00:49.797 回答
1
#!/usr/bin/env perl

use strict;
use warnings;
use Data::Dumper;

my %data = (
    ABC => [1, 2],
     1  => [11, 12, 13, 14],
     13 => [17, 20] 
);
my %hash;

sub modify_hash {
    my ($base, $ref) = @_;
    for my $k (keys %$ref) {
        if (exists $base->{$k}) {
            $ref->{$k} = $base->{$k};
            delete $base->{$k};
        }
        modify_hash($base, $ref->{$k});
    }
}

map { %{$hash{$_}} = map { $_ => {}; } @{$data{$_}}; } keys %data;
map { modify_hash(\%hash, $hash{$_}); } keys %hash;
print Dumper(\%hash);

输出:

$VAR1 = {
          'ABC' => {
                     '1' => {
                              '11' => {},
                              '13' => {
                                        '17' => {},
                                        '20' => {}
                                      },
                              '12' => {},
                              '14' => {}
                            },
                     '2' => {}
                   }
        };
于 2012-08-08T13:27:00.683 回答
1

您可以使用我在此处定义的代码:如何在 Perl 中将多个散列合并为一个散列?

如此定义@hash_list

my @hash_list 
    = { map { ref() eq 'ARRAY' ? { map {; $_ => {} } @$_ } : $_ } 
        %{{ ABC => [1, 2]
          ,  1  => [11, 12,13,14]
          , 13  => [17,20] 
          }}
      };
于 2012-08-07T23:11:59.877 回答