开发者

How can I convert one Perl hash to another using the keys?

开发者 https://www.devze.com 2022-12-24 09:04 出处:网络
I\'ve just started diving in to the crazy world that is perl and have come across a problem that I cannot seem to wrap my head around. Specifically I need to be able to convert from one hash structure

I've just started diving in to the crazy world that is perl and have come across a problem that I cannot seem to wrap my head around. Specifically I need to be able to convert from one hash structure to another, that uses the keys/values as the new hashes keys/values.

An example:

Input hash:

    my %original_hash = (
    first_key => {  some_key => "apples",
                    another_key => "chips",
                    #potentially more here
                 },
     second_key => {  more_of_same => "dogs", 
                      its_another => "cats",
                      #potentially more here 
                   }
      );

Output hash:

my %final_hash = ( 
   some_key => { 
                    apples => { 
                                more_of_same => "dogs", 
                                its_another => "cats", 
                              } 
               } ,
   another_key => { 
                    chips => { 
                                more_of_same => 开发者_JAVA技巧"dogs", 
                                its_another => "cats",
                              } 
                  } 

);

And yes I do want the second_key's data repeated in the final_hash, as there will be an array of the original_hashes that are inputted. The first element becomes the base-case, and all other elements may append or remove from that list.

If anyone has any suggestions on how to go about doing this that would be greatly appreciated!


Here is another way

my %final_hash;

my %tmp = %{$original_hash{first_key}}; 
my $val = $original_hash{second_key};

while ( my ($k,$v) = each %tmp) {
    $final_hash{$k} =  { $v => $val };
}


print Dumper (\%final_hash);


Okay, Sinan is right, it's very hard to guess your problem, but the following code seems to do what you want ... or at least it produces the listed output.... :)

use strict;
use warnings;
use Data::Dumper;
$Data::Dumper::Deepcopy = 1;

my %original_hash = (
    first_key => {  some_key => "apples",
                    another_key => "chips",
                    #potentially more here
             },
 second_key => {  more_of_same => "dogs",
                  its_another => "cats",
                  #potentially more here
               }
);


my %final_hash;

for my $key ( keys %{ $original_hash{first_key} } ) {
        $final_hash{$key} = { 
           $original_hash{first_key}->{$key} 
                 => $original_hash{second_key}
           };
}


print Dumper(\%final_hash);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号