http://www.perlmonks.org?node_id=685250

gwhite has asked for the wisdom of the Perl Monks concerning the following question:

I have an older legacy module that returns me a hash with a couple of hundred keys. This module is in use by several other parts of the application so rewriting it is not desirable. The hash that is returned to me has some of the values as hash references. My desire is to write the hash out as XML using XML::Simple. Part of the trouble is that some of the keys have spaces in them which means the XML is not well formed. Keys in the hash references also suffer this affliction.

What I cannot get my mind around is how to parse through the hash and hash references, then use a regex to strip the spaces from the keys, and result in a hash with XML valid keys.

The hash looks something like: $global{'title'}='Report for today' $global{'data 1'}{title}='My data 1 title' $global{'data 1'}{data}= (ref to hash) $global{'data 1'}{footer}='My footer' $global{'data 2'}{title}='My data 2 title' $global{'data 2'}{subtitle}='Data 2 subtitle' $global{'data 2'}{data}= (ref to hash) $global{'data 2'}{'data percentages'}= (ref to hash) $global{'data 2'}{'data raw'}= (ref to hash) $global{'data 2'}{footer}='Footer for data 2' and so on..

Once I have printed the XML file, I am done with the data so changing the keys at this point will not impact any other processes. Here is what I have come up with at this point (but it does not seem to be affecting the hash references)

sub hash_remove_key_space { my $in_hash = shift; my %work_hash = %$in_hash; my %output_hash; foreach my $ckey(keys %work_hash){ my $value; if (ref($work_hash{$ckey}) eq "HASH") { $value = hash_remove_key_space($work_hash{$ckey}); } else { $value = $work_hash{$ckey}; } my $temp = $ckey; $temp =~ s|\s||isg; $output_hash{$temp} = $value; } return \%output_hash; } corrected code - per Sam

Any insight would be appreciated

g_White