How can I determine if a Perl hash matches a key mapping with an undefined value?

I need to determine if the Perl hash has the given key, but this key will map to undef. In particular, the motivation for this is that if the logical flags when using getopt() with a hash link are passed to it. I have already searched both this site and google, and exists() and defined() do not seem to be applicable to the situation, they just see that the value for this key is undefined, they do not check if the hash really has a key. If I'm RTFM here, please provide me with a guide that explains this.

+7
perl exists key hash defined
source share
3 answers

exists () and defined () do not seem to be applicable for the situation, they just see that the value for the given key is undefined, they do not check if the hash really has a key

Wrong. This is really 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"; } 

gives:

 $ 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 on the command line in perldoc -f defined and perldoc -f exists (or read the documentation for all methods in perldoc perlfunc *). The official web documentation is here:

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

+26
source share

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

EXPR exists

Given an expression that indicates a hash 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}; } 
+11
source share

Short answer:

  if ( exists $hash{$key} and not defined $hash{$key} ) { ... } 
+6
source share

All Articles