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

I want to test the existence of a hash key so that the case of the key does not matter. I would prefer to do this in the normal way of
if(exists($data{$str})) {
where any of abcd, aBcd, AbcD and so on would pass for the key of abcd.
What is the simplest way of achieving this?

Replies are listed 'Best First'.
Re: Case insensitive hash key existance
by Your Mother (Archbishop) on Nov 22, 2017 at 15:44 UTC

    Probably $data{fc $str} (in every instance of using the hash key) if your Perl is new enough. $data{lc $str} otherwise. The later may come with surprises if you deal with "wide characters."

Re: Case insensitive hash key existance
by haukex (Archbishop) on Nov 22, 2017 at 15:47 UTC
Re: Case insensitive hash key existance
by kennethk (Abbot) on Nov 22, 2017 at 16:00 UTC
    If you have an existing hash (thus fc is not an option), you can grep the key set against a case-insensitive regular expression:
    if(grep /^\Q$str\E$/i, keys %data) { # case-insensitive exists
    This solves an immediate problem, though making sure your keys were well-formed in the first place would probably be cleaner.

    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

      :P

      if ( grep fc $str eq fc $_, keys %data ) { # case-insensitive exists

      Or to "fix" the data-

      $data{fc$_} = delete $data{$_} for keys %data;

      As this example should make clear, and haukex's links explained, the entire operation is probably a bad idea as it is destructive (or at least has the appearance of being so if the plain folding is done without deleting.

      Thanks for all the replies. I take the point about well formed data for keys and normally I would not want to do such a thing.
      However, there are reasons why it is OK in this case.
      The grep suggestion does just what I want.

        Be warned of the massive performance hit. It replaces an O(1) lookup with than O(N) lookup. That's not good, but it's not so bad ...except that this is likely used in another another loop. Then that O(N) or O(N^2) loop because O(N^2) or O(N^3), and things start to crawl.

Re: Case insensitive hash key existance
by Anonymous Monk on Nov 22, 2017 at 15:57 UTC
    Use a second hash to store the uppercased version of the original key, then store the data using that uppercased string. Q.E.D.
A reply falls below the community's threshold of quality. You may see it by logging in.