CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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

 



pearl0817
New User

Aug 17, 2011, 7:57 AM

Post #1 of 3 (1187 views)
searching for empty keys in multidimensional hash Can't Post

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

Post #2 of 3 (1165 views)
Re: [pearl0817] searching for empty keys in multidimensional hash [In reply to] Can't Post

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

Post #3 of 3 (1162 views)
Re: [BillKSmith] searching for empty keys in multidimensional hash [In reply to] Can't Post

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

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives