Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Perl Misc (http://www.velocityreviews.com/forums/f67-perl-misc.html)
-   -   Searching an example for a defined hash value of a nonexisting hash key (http://www.velocityreviews.com/forums/t887343-searching-an-example-for-a-defined-hash-value-of-a-nonexisting-hash-key.html)

Ralf Baerwaldt 07-20-2004 02:47 PM

Searching an example for a defined hash value of a nonexisting hash key
 
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'}));
----


Paul Lalli 07-20-2004 03:05 PM

Re: Searching an example for a defined hash value of a nonexistinghash key
 
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


All times are GMT. The time now is 03:17 PM.

Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57