[Israel.pm] FW: check if hash is defined - without the keys

Gaal Yahas gaal at forum2.org
Thu Jan 22 06:01:41 PST 2009

Can you specify what you want more exactly? You have 25 elements and
aren't sure if their values are defined? You'll have to visit every
element, of course, although if you don't like the explicit loop you
can hide it away in one of perl's list operators.

If you don't care about which element fails, just whether there are at
all any undefined values:

$count = grep { defined $_ } values %hash;  # $count of the number of
defined values in %hash
die "Some keys not defined" unless 25 == $count;

This assumes the elements themselves are there, and that no other elements.

(You can also use a fancy hash slice instead of "values", but I won't
go into that unless you want me to...)

To make things perfectly clear: a hash has a certain number of
elements. This is precisely the number of keys. Each key has a value,
which may be undef, but that still counts as an existing element. "if
$hash{foo}" tests the truth of a value (it's false when the element
doesn't exist, or when it is undefined, or for other defined values of
falsehood). "if exists $hash{foo}" tests whether the element exists.
"if defined $hash{foo}" will return false if there's no element foo,
OR if foo exists but is undef.

Don't bother with the scalar value of %hash. It contains some
information about the internal state of the hash, which is almost
never something you care about. It's a misfeature of the language that
this is so visible. In your case for example it's useless: if the hash
grew and shrank, the behavior you observed won't take place.

On Thu, Jan 22, 2009 at 3:31 PM, Chanan Berler <chananb at centerity.com> wrote:
> Hi All,
> I got a hash with key1…key25, I am looking to know if the keys are defined
> or not.
> But I don't like the way like: if defined($hash{key1}) or …..
> defined($hash{key5})
> I also don't like much the idea of looping over the keys…
> Q: is there a way to check if hash was defined or not….using the defined
> function showed a warning…
> PS: I can stop using the use strict / warnings – and try this if (%tvc or
> %tvw) – and it works…
>      But I still want to use them…
> Thanks
> Chanan
> _______________________________________________
> Perl mailing list
> Perl at perl.org.il
> http://perl.org.il/mailman/listinfo/perl

Gaal Yahas <gaal at forum2.org>

More information about the Perl mailing list