9

I am writing a script which is likely to be modified by users. Currently I am storing the configuration settings inside the script. It exists in the form of a hash-of-hashes.

I would like to guard against people accidentally using lowercase characters in the hash keys, because that will break my script.

It would be simple to inspect the hash keys and merely issue warnings for any keys with lowercase characters, but I would rather fix the case sensitivity automatically.

In other words, I want to convert all the hash keys in the top-level hash to uppercase.

4 Answers 4

17

Andy's answer is a good answer, except he ucs every key, and then ucs it again if it doesn't match.

This ucs it once:

%hash = map { uc $_ => $hash{$_} } keys %hash;

But since you spoke of users storing keys, a tie is a much more sure way, even if slower.

package UCaseHash;
require Tie::Hash;

our @ISA = qw<Tie::StdHash>;

sub FETCH { 
    my ( $self, $key ) = @_;
    return $self->{ uc $key };
}

sub STORE { 
    my ( $self, $key, $value ) = @_;
    $self->{ uc $key } = $value;
}

1;

And then in main:

tie my %hash, 'UCaseHash'; 

That's a show. The tie "magic" encapsulates it, so the users can't unknowingly mess with it.

Of course, as long as you're using a "class", you can pass in the config file name and initialize it from there:

package UCaseHash;
use Tie::Hash;
use Carp qw<croak>;

...

sub TIEHASH { 
    my ( $class_name, $config_file_path ) = @_;
    my $self = $class_name->SUPER::TIEHASH;
    open my $fh, '<', $config_file_path 
        or croak "Could not open config file $config_file_path!"
        ;
    my %phash = _process_config_lines( <$fh> );
    close $fh;
    $self->STORE( $_, $phash{$_} ) foreach keys %phash;
    return $self;
}

Where you would have to call it like:

tie my %hash, 'UCaseHash', CONFIG_FILE_PATH;

...assuming some constant CONFIG_FILE_PATH.

4
  • 1
    You know, there's a module on CPAN which does this. No need to code it yourself: Hash::Case, see search.cpan.org/dist/Hash-Case
    – bart
    Nov 21, 2008 at 22:28
  • Your method will overwrite the entire hash, while Andy's method will only overwrite lowercased ones. Unless you expect the hash to contain a terrible lot of lowercase keys (not likely in this scenario), it is not going to be faster. Nov 21, 2008 at 22:35
  • 1
    Thanks for the heads up, bart. I forgot the first rule of Perl Club: Don't talk before you've checked CPAN. My post started out simple illustration of a tied class, and then I got fancy. Doh!
    – Axeman
    Nov 21, 2008 at 23:03
  • 1
    Appreciate the point, Leon. But I don't like to throw away data already computed, it's not necessarily about speed. Mine is a more functional expression, IMO.
    – Axeman
    Nov 21, 2008 at 23:17
12

Walk through the hash and replace any lowercase keys with their uppercase equivalents, and delete the old ones. Roughly:

for my $key ( grep { uc($_) ne $_ } keys %hash ) {
    my $newkey = uc $key;
    $hash{$newkey} = delete $hash{$key};
}
0

This will convert multi level hash to lowercase

my $lowercaseghash = convertmaptolowercase(\%hash);

sub convertmaptolowercase(){
    my $output=$_[0];
    while(my($key,$value) = each(%$output)){
        my $ref;
        if(ref($value) eq "HASH"){
            $ref=convertmaptolowercase($value);
        } else {
           $ref=$value;
        }
        delete $output->{$key}; #Removing the existing key
        $key = lc $key;
        $output->{$key}=$ref; #Adding new key
    }
    return $output;
}
-1

Came this way looking for an answer and thought I'd share some of my learning. To ensure compatibility between GET/POST parameters, templates, and stored procedures I wanted to ensure all keys obtained via $cgi->Vars were in upper case and there were no residual lower case 'duplicate' keys. Here's the basic script...

use CGI;
use Data::Dumper;

my $cgi = CGI->new;

print "Content-Type: text/html\n\n";

$params = $cgi->Vars();

print "<p>Before - ", Dumper($params);

map { 
    if ( $_ =~ qr/[a-z]+/mp ){ 
        $params->{uc $_} = $params->{$_}; 
        delete($params->{$_}); 
    }  
} keys %{$params};

print "<p>After - ", Dumper($params);

exit;

The output looks like this...

Before - $VAR1 = { 'table' => 'orders', 'SALESMAN_ID' => '2', 'customer_id' => '49' };

After - $VAR1 = { 'SALESMAN_ID' => '2', 'TABLE' => 'orders', 'CUSTOMER_ID' => '49' };
1
  • There are a few weird things going on in this code. You're basically doing what Axeman did, but with some not-so-great practices and some extra steps. Nov 1, 2022 at 23:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.