use strict; use warnings; use Data::Dumper; # Original $data edited to make it easier (for my old eyes) to read. # my $dataItems = [ { Ad1 => q{20 North Central St.}, status => q{Main}, City => q{NY}, zCode => q{0002}, name => q{John D}, ID => q{2222}, state => q{TO} }, { Ad1 => q{15 South Street}, status => q{Property}, City => q{NY}, zCode => q{0002}, name => q{John V}, ID => q{2222}, state => q{TO} }, { Ad1 => q{100 main St.}, status => q{Extra}, City => q{BO}, zCode => q{0007}, name => q{Tony Star}, ID => q{2222}, state => q{UA} }, { Ad1 => q{5540 Chelsea Avenue}, status => q{Cabin}, City => q{NE}, zCode => q{4562}, name => q{Carly Simon}, ID => q{2222}, state => q{TO} }, { Ad1 => q{12th Street}, status => q{Main}, City => q{NM}, zCode => q{2334}, name => q{Charles D}, ID => q{1111}, state => q{CA} }, { Ad1 => q{44 Dell St}, status => q{Extra}, City => q{MA}, zCode => q{9857}, name => q{Marie Doe}, ID => q{1111}, state => q{CA} }, { Ad1 => q{33 Dust Road}, status => q{Property}, City => q{ET}, zCode => q{3345}, name => q{Chapim Thor}, ID => q{1111}, state => q{CA} }, { Ad1 => q{01 Charles St}, status => q{Cabin}, City => q{CA}, zCode => q{2334}, name => q{Claud Odur}, ID => q{1111}, state => q{CA} }, { Ad1 => q{1AAAA}, status => q{Main}, City => q{AA}, zCode => q{TTTT}, name => q{AKAKAK}, ID => q{8888}, state => q{PP} }, { Ad1 => q{2AAAA}, status => q{Test}, City => q{BB}, zCode => q{WWWW}, name => q{BXBXBX}, ID => q{8888}, state => q{HH} }, { Ad1 => q{CCCCC}, status => q{Property}, City => q{ET}, zCode => q{3345}, name => q{Chapim Thor}, ID => q{8888}, state => q{CA} }, { Ad1 => q{DDDDD}, status => q{Cabin}, City => q{CA}, zCode => q{2334}, name => q{Claud Odur}, ID => q{8888}, state => q{CA} }, ]; # Re-arrange the reftoAoH $data into a reftoHoHoH $rhByID using hash # slices. # my $rhByID = {}; my @subKeys = qw{ Ad1 City zCode name state }; foreach my $rhItem ( @{ $dataItems } ) { @{ $rhByID->{ $rhItem->{ ID } }->{ $rhItem->{ status } } }{ @subKeys } = @{ $rhItem }{ @subKeys }; } # Now add in the new keys and associated values for those IDs that have # a "Extra" sub-key, again using hash slices. I've included "state" in # case it had been omitted from the OP code by mistake. # my @newKeys = qw{ newAd1 newCity newZip newName newState }; foreach my $id ( keys %{ $rhByID } ) { next unless exists $rhByID->{ $id }->{ Extra }; @{ $rhByID->{ $id }->{ Main } }{ @newKeys } = @{ $rhByID->{ $id }->{ Extra } }{ @subKeys }; } # Dump the new data structure. # print Data::Dumper ->new( [ $rhByID ], [ qw{ rhByID } ] ) ->Sortkeys( 1 ) ->Indent( 1 ) ->Dumpxs();