I came upon the need to ensure that the keys for values slurped into a nested hash via XML::Simple reading an XML config file matched what I was referring to them as in my script. After playing around with various Tie::* modules I decided it was just easier for me to force the entire nested hash into one or the other case for my access. The following was the outcome of my trials: Note that duplicate name keys with differing case will be squashed. Now this hash:
$nestedhash = { 'REJECTED' => 'REJECTED', 'FREQUENCY' => 'FREQUENCY', 'INCOMING' => { 'DIR' => 'DIR' }, 'CONNECTIONSTRING' => 'CONNECTIONSTRING', 'REGEX' => 'REGEX', 'EMAIL' => { 'GENERAL' => 'GENERAL', 'CRITICAL' => 'CRITICAL', 'SMTPSERVER' => 'SMTPSERVER' }, 'DIR' => ['DIR1', 'DIR2'] };
becomes this:
$VAR1 = { 'incoming' => { 'dir' => 'DIR' }, 'frequency' => 'FREQUENCY', 'regex' => 'REGEX', 'rejected' => 'REJECTED', 'dir' => [ 'DIR1', 'DIR2' ], 'connectionstring' => 'CONNECTIONSTRING', 'email' => { 'general' => 'GENERAL', 'critical' => 'CRITICAL', 'smtpserver' => 'SMTPSERVER' } };
Update: Good eye, blakem, I never had occasion to run my hash through twice, but the added check fixes that problem.
sub force_uc_hash { my $hashref = shift; foreach my $key (keys %{$hashref} ) { $hashref->{uc($key)} = $hashref->{$key}; force_uc_hash($hashref->{uc($key)}) if ref $hashref->{$key} eq + 'HASH'; delete($hashref->{$key}) unless $key eq uc($key); } } sub force_lc_hash { my $hashref = shift; foreach my $key (keys %{$hashref} ) { $hashref->{lc($key)} = $hashref->{$key}; force_lc_hash($hashref->{lc($key)}) if ref $hashref->{$key} eq + 'HASH'; delete($hashref->{$key}) unless $key eq lc($key);; } }

Replies are listed 'Best First'.
Re: Force nested hashes to upper/lower case keys
by blakem (Monsignor) on Aug 29, 2002 at 19:20 UTC
    It looks like the key deletion needs a bit more checking first. You're deleting all the keys even if they already conform to the capitalization rules. Try running a hash through your functions twice in a row. I think you'll be surprised at whats left...
    use Data::Dumper; my $hash = {dog=>'cat',PIG=>'cow'}; print Dumper $hash; force_uc_hash($hash); force_uc_hash($hash); print Dumper $hash;

    -Blake