Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Perl > Perl Misc > Searching an example for a defined hash value of a nonexisting hash key

Reply
Thread Tools

Searching an example for a defined hash value of a nonexisting hash key

 
 
Ralf Baerwaldt
Guest
Posts: n/a
 
      07-20-2004
In "man perlfunc" I found:

-----
defined EXPR
....
When used on a hash element, it tells you whether
the value is defined, not whether the key exists
in the hash.
-----

Is it really possible to have a defined value on a
nonexisting key ? Can someone give a sample ?

If I want to print the defined values of a hash, do I have to prove
if the keys exists ? Up to now I just prove for a defined value
assuming that in this case the key must exists, i.e.

----
#!/usr/bin/perl
my %h;
....
print "Val=$h{'KEY'}\n" if defined($h{'KEY'});
----

or must I do:

----
print "Val=$h{'KEY'}\n" if (exists($h{'KEY'}) and (defined($h{'KEY'}));
----

 
Reply With Quote
 
 
 
 
Paul Lalli
Guest
Posts: n/a
 
      07-20-2004
On Tue, 20 Jul 2004, Ralf Baerwaldt wrote:

> In "man perlfunc" I found:
>
> -----
> defined EXPR
> ...
> When used on a hash element, it tells you whether
> the value is defined, not whether the key exists
> in the hash.
> -----
>
> Is it really possible to have a defined value on a
> nonexisting key ? Can someone give a sample ?


No. The point of that manual text is that a key/value pair can exist
without the value being defined.

As relates to Perl hashes, boolean truth implies defined, and defined
implies exists.

> If I want to print the defined values of a hash, do I have to prove
> if the keys exists ?


No. If the value is defined, it exists.

This is a logical series of steps:
if (exists ($hash{key})) {
print "key exists in hash\n";
if (defined ($hash{key})){
print "key's value is defined in hash\n";
if ($hash{key}){
print "key's value is a true value\n";
} else {
print "key's value is false\n";
}
} else {
print "key's value is not defined, and therefore false\n";
}
} else {
print "key does not exist. Value is therefore undefined and false\n";
}


HTH,
Paul Lalli
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
hash of hash of hash of hash in c++ rp C++ 1 11-10-2011 04:45 PM
new in CGI::Session::Driver::postgredsql nonexisting IDK Perl Misc 11 06-29-2007 01:52 PM
hash key to var name of value hash key value Une bévue Ruby 5 08-10-2006 04:05 PM
#if (defined(__STDC__) && !defined(NO_PROTOTYPE)) || defined(__cplusplus) Oodini C Programming 1 09-27-2005 07:58 PM
sort multi-key hash by value and print out with key value pairs Antonio Quinonez Perl Misc 2 08-14-2003 10:56 PM



Advertisments