Reputation: 227
I have a hash of hash of hash as
hash_1 =>{
hash_2=>{
a1 => {
1 => m,
2 => x,
3 => n
},
a2 => {
1 => a,
2 => x,
3 => b
},
a3 => {
1 => c,
2 => y,
3 => d
},
a4 => {
1 => i,
2 => y,
3 => j
},
},
};
Now I want to delete the key "hash_2" and and add new keys in place of "hash_2" which depends on the value of the key "2" inside each hashes a1, a2, a3... So, like here we have two different values for the key "2" : x and y. So I want this values to be in place of the key of the first hash "hash_2" and create a new hash map altogether. So end result should be :
hash_1 =>{
x=>{
a1 => {
1 => m,
2 => x,
3 => n
},
a2 => {
1 => a,
2 => x,
3 => b
},
},
y => {
a3 => {
1 => c,
2 => y,
3 => d
},
a4 => {
1 => i,
2 => y,
3 => j
},
},
};
I checked How to replace a Perl hash key? but could not get how to make a value of a key as a key. I tried deleting the hash_2 but was not successful(using the delete keyword). Thanks.
Upvotes: 0
Views: 87
Reputation: 126722
Like this, perhaps?
use strict;
use warnings 'all';
use Data::Dump;
my $hash_1 = {
hash_2 => {
a1 => { 1 => "m", 2 => "x", 3 => "n" },
a2 => { 1 => "a", 2 => "x", 3 => "b" },
a3 => { 1 => "c", 2 => "y", 3 => "d" },
a4 => { 1 => "i", 2 => "y", 3 => "j" },
}
};
{
my $data = delete $hash_1->{hash_2};
for my $key ( keys %$data ) {
my $item = $data->{$key};
$hash_1->{ $item->{2} }{ $key } = $item;
}
}
dd $hash_1;
{
x => {
a1 => { 1 => "m", 2 => "x", 3 => "n" },
a2 => { 1 => "a", 2 => "x", 3 => "b" },
},
y => {
a3 => { 1 => "c", 2 => "y", 3 => "d" },
a4 => { 1 => "i", 2 => "y", 3 => "j" },
},
}
Upvotes: 1