use strict; use warnings; use Data::Dumper; my %global; $global{'title'}='Report for today'; $global{'data 1'}{title}='My data 1 title'; $global{'data 1'}{data}= {}; $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}= {}; $global{'data 2'}{'data percentages'}= {}; $global{'data 2'}{'data raw'}= {}; $global{'data 2'}{footer}='Footer for data 2'; unspace_keys( \%global ); print Dumper \%global; sub unspace_keys { my $hash_ref = shift; foreach my $spaced_key ( grep /\s/, keys %{ $hash_ref } ) { ( my $new_key = $spaced_key ) =~ s/\s+//g; if ( exists $hash_ref->{$new_key} ) { die "unspaced key '$new_key' exists"; } $hash_ref->{$new_key} = $hash_ref->{$spaced_key}; delete $hash_ref->{$spaced_key}; } unspace_keys( $_ ) for grep { ref $_ eq ref {} } values %{ $hash_ref }; return; } __END__ $VAR1 = { 'data2' => { 'subtitle' => 'Data 2 subtitle', 'data' => {}, 'title' => 'My data 2 title', 'dataraw' => {}, 'datapercentages' => {}, 'footer' => 'Footer for data 2' }, 'title' => 'Report for today', 'data1' => { 'data' => {}, 'title' => 'My data 1 title', 'footer' => 'My footer' } };