Home: Perl Programming Help: Intermediate:
searching for empty keys in multidimensional hash



pearl0817
New User

Aug 17, 2011, 7:57 AM


Views: 1755
searching for empty keys in multidimensional hash

Hello,
This is my first time posting here. I have researched this prior to posting, but couldn't find any solution. I need to clean up hashes stored in our database. Some of them have empty keys, so those have to be deleted. Here's a sample hash:

Code
'Groups' 
{
'A' => {
'' => '45',
'allMembers' => '46,69,45'
},
'B' => {
'BO' => '52',
'allMembers' => '52'
},
'D' => {
'Dive Ops' => '105',
'Diving' => '274',
'allMembers' => '105,274'
},
'F' => {
'FO' => '276',
'allMembers' => '276'
},
'SP' => {
'SP' => '275',
'allMembers' => '275'
},
'rt' => {
'' => '91',
'allMembers' => '119,91'
}
}

So taking the first set as an example

Code
'A' => { 
'' => '45',
'allMembers' => '46,69,45'
},

The first value has an empty key,it has to be deleted, and then since there are no more items actually, A has to be deleted altogether. I have a problem with syntax,how do I loop through this hash and single out the empty keys?
Any help would be greatly appreciated.
Thanks!


BillKSmith
Veteran

Aug 17, 2011, 8:45 PM


Views: 1733
Re: [pearl0817] searching for empty keys in multidimensional hash

Looping is straightforward. Doing all the dereferencing correctly is another matter. Half the trick is making reasonable names for the new variables. I hope that I have succeeded.


Code
use strict; 
use warnings;
use Data::Dumper;
my $Groups = {
A => {
'' => '45',
'allMembers' => '46,69,45',
},
B => {
'BO' => '52',
'allMembers' => '52' },
D => {
'Dive Ops' => '105',
'Diving' => '274',
'allMembers' => '105,274',
},
F => {
'FO' => '276',
'allMembers' => '276',
},
SP => {
'SP' => '275',
'allMembers' => '275',
},
rt => {
'' => '91',
'allMembers' => '119,91',
},
};

foreach my $sub_groups (values %$Groups) {
foreach my $member (keys %$sub_groups) {
delete $sub_groups->{$member} if !$member;
}
}

print Dumper $Groups;

while (my ($group_name, $sub_groups) = each %$Groups) {
delete $Groups->{$group_name} if 1 >= scalar keys %$sub_groups ;
}

print Dumper $Groups;

Good Luck,
Bill


pearl0817
New User

Aug 18, 2011, 9:26 AM


Views: 1730
Re: [BillKSmith] searching for empty keys in multidimensional hash

Bill, Thanks a bunch! Your solution works perfectly. I was SO lost :)
Thanks again
Victoria