Erik Olson Erik Olson -4 years ago 96
Perl Question

Hashes: testing a key

A program reads a very large dictionary-style TXT file into a hash. Sometimes, there is a lower case version of a key that is preferable. My solution below is clumsy because it searches twice even if we already know the

version exists:

if ( exists $hash{ lc $key } ) {
$key = lc $key;
if ( exists $hash{ $key } ) {
# lot of code involving $key
else {
# the key doesn't exist, other code

Is there a way to avoid two
tests? If
lc $key
exists I want to do the identical code to it as in the second
but I need to know which version,
or not, of
to use. I'm hoping to condense it to one

Knowing the case of the valid key is important for the rest of the program since it is used to look up information in another hash.

Answer Source
if ( my ($real_key) = grep { exists($hash{$_}) } lc($key), $key ) {
} else {


my $real_key = exists($hash{lc($key)}) ? lc($key) : $key;

if (exists($hash{$real_key})) {
} else {

Sure, it still searches twice, but so what? You could use List::Utils's first, but I think replacing a hash lookup with a sub call could actually slow down the code!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download