How can I determine if a Perl hash contains a key mapping to an undefined value?

Alex Marshall picture Alex Marshall · Jan 23, 2010 · Viewed 25.1k times · Source

I need to determine if a Perl hash has a given key, but that key will be mapped to an undef value. Specifically, the motivation for this is seeing if boolean flags while using getopt() with a hash reference passed into it. I've already searched both this site and google, and exists() and defined() don't seem to be applicable for the situation, they just see if the value for a given key is undefined, they don't check if the hash actually has the key. If I an RTFM here, please point me to the manual that explains this.

Answer

Ether picture Ether · Jan 24, 2010

exists() and defined() don't seem to be applicable for the situation, they just see if the value for a given key is undefined, they don't check if the hash actually has the key

Incorrect. That is indeed what defined() does, but exists() does exactly what you want:

my %hash = (
    key1 => 'value',
    key2 => undef,
);

foreach my $key (qw(key1 key2 key3))
{
    print "\$hash{$key} exists: " . (exists $hash{$key} ? "yes" : "no") . "\n";
    print "\$hash{$key} is defined: " . (defined $hash{$key} ? "yes" : "no") . "\n";
}

produces:

$hash{key1} exists: yes
$hash{key1} is defined: yes
$hash{key2} exists: yes
$hash{key2} is defined: no
$hash{key3} exists: no
$hash{key3} is defined: no

The documentation for these two functions is available at the command-line at perldoc -f defined and perldoc -f exists (or read the documentation for all methods at perldoc perlfunc*). The official web documentation is here:

*Since you specifically mentioned RTFM and you may not be aware of the locations of the Perl documentation, let me also point out that you can get a full index of all the perldocs at perldoc perl or at http://perldoc.perl.org.