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

Hi

I am using Hash to store some values, say i have a hash like this

%hash = ("abc" => "1", "def" => "2", "ghi" => "3", );

In this case, How can i match the exact value for Key of hash ?, i wrote like this
if($match =$hash{$input}) { print "MATCHED VALUE IS \"$match\"...\n"; }

This works fine if "$input" exactly equals to "abc" or "def" or "ghi", but fails if "AbC" of "ABC" etc. How can i match keys with case insensitive so that anything i supply will Pass

Thanks,
ShekarKCB

Replies are listed 'Best First'.
Re: Matching case insensitively in Hashes
by ELISHEVA (Prior) on Feb 11, 2009 at 06:47 UTC
    1. use only lower case keys when you set up your hash
    2. before you use the key to retrieve a value, lowercase it, like this:  $hash{lc $input}

    Also, your syntax in the if statement isn't quite right. You are assigning a value to $match rather than comparing match to the hash value. To compare the values use:

    • if ($match eq $hash{$input}) { ... } if your hash values can be strings containing something other than numbers. eq is the string comparison operator.
    • if ($match == $hash{$input}) { ... } if the hash values are always numbers. == is the numeric comparison operator.

    See perlop for details.

    Best, beth

    Update: added clarifications on "use ... keys"

      Also, your syntax in the if statement isn't quite right. ...

      I believe the idea was simply to test if there exists an entry for $input in the hash and the associated value evaluates to 'true', i.e.

      if ($hash{$input}) { ... }

      The additional assignment to $match is presumably just for easier subsequent access to the value (such as in the print statement)...  (Only the OP will be able to tell, however, what the real intention was :)

Re: Matching case insensitively in Hashes
by CountZero (Bishop) on Feb 11, 2009 at 06:54 UTC
    Tie::CPHash will do what you want.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

      Thank you all for the reply
      My stuff worked with Tie::CPHash

      Thanks,
      ShekarKCB