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

Hi monks,

Can I get the value from an hash with case insensitive key.

Example:

%h=('adobe'=>'abcd','big boss'='gcd');

I want the value abcd when i print $h{'AdOBe'}.

How can i get this.

Thanks.

Replies are listed 'Best First'.
Re: Hash Keys case independent
by Joost (Canon) on May 04, 2004 at 15:13 UTC
Re: Hash Keys case independent
by edan (Curate) on May 04, 2004 at 15:13 UTC
Re: Hash Keys case independent
by Limbic~Region (Chancellor) on May 04, 2004 at 15:16 UTC
Re: Hash Keys case independent
by davido (Cardinal) on May 04, 2004 at 15:21 UTC
    You can not do it with a simple hash. However, a tied hash may have whatever qualities you desire.

    There are the following modules on CPAN that might be helpful:

    Personally I would probably start with Tie::Hash, and create your own case-insensitive hash starting with that framework. tie and perltie will contain additional info on the details of tieing hashes.

    Update: Fixed a few module names. Thanks Limbic~Region.


    Dave

      You can not do it with a simple hash.

      Yes you can. However, that does not mean that you should :-)

      my %h = ( 'aDobe' => 'abcd', 'big boss' => 'gcd', 'ADOBe' => 'abcd2' ) +; my $str = 'AdOBE'; for ( keys %h ) { print "$h{$_}\n" if lc $_ eq lc $str; }
Re: Hash Keys case independent
by Itatsumaki (Friar) on May 04, 2004 at 15:16 UTC

    One way is to standardize on one case for all your keys on insertion, then to force case on retrieval, like this:

    %h = ( lc('adobe') => 'abcd', lc('big boss') => 'gcd', ); my $key = 'AdOBe'; $key = lc($key); print $key;
    -Tats
Re: Hash Keys case independent
by EdwardG (Vicar) on May 04, 2004 at 15:14 UTC

    As you have probably guessed, perl is case sensitive, so you are paddling upstream from the start.

    But it is easy, depending on your circumstance, to force either the keys, or the subsequent comparison, to lower case using lc or upper case using uc.

    For example

    print $h{lc 'AdOBe'};