views:

401

answers:

3

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.

+11  A: 

If I'm reading your question correctly, I think you are confused about exists. From the documentation:

exists EXPR

Given an expression that specifies a hash element or array element, returns true if the specified element in the hash or array has ever been initialized, even if the corresponding value is undefined.

For example:

use strict;
use warnings;

my %h = (
    foo => 1,
    bar => undef,
);

for my $k ( qw(foo bar baz) ){
    print $k, "\n" if exists $h{$k} and not defined $h{$k};
}
FM
+13  A: 

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.

Ether
+5  A: 

Short answer:

 if ( exists $hash{$key} and not defined $hash{$key} ) {
    ...
 }
Adam Kennedy