Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: testing a non-existant hash entry...how to handle

by ton (Friar)
on Mar 01, 2002 at 19:40 UTC ( [id://148660]=note: print w/replies, xml ) Need Help??


in reply to testing a non-existant hash entry...how to handle

The best way to check for the existance of a key in a hash is to use the exists function. Checking against the hash value doesn't always work, because you could have that value be 0. In fact, you could have that value be undef, so defined does not always give the right behavior either. Example:
use strict; my %hash; my $result; $hash{'foo'} = 0; $hash{'bar'} = undef; if ($hash{'foo'} && $hash{'bar'}) { $result = 'present'; } else { $result = 'NOT present'; } print "Direct checking thinks 'foo' and 'bar' are $result in \$hash.\n +"; if (defined($hash{'foo'}) && defined($hash{'bar'})) { $result = 'present'; } else { $result = 'NOT present'; } print "'defined' checking thinks 'foo' and 'bar' are $result in \$hash +.\n"; if (exists($hash{'foo'}) && exists($hash{'bar'})) { $result = 'present'; } else { $result = 'NOT present'; } print "'exists' checking thinks 'foo' and 'bar' are $result in \$hash. +\n";
-Ton
-----
Be bloody, bold, and resolute; laugh to scorn
The power of man...

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://148660]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2024-04-19 20:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found