in reply to Re^2: how to identify a null hash value
in thread how to identify a null hash value

ahhh, I see. Again though, it does appear from what you've posted that $value DOES contain data, and if that's the case, all of your tests will be true.

One way to see if I'm correct in thinking you've got a defined value (hashref) is this:

print "it's a hashref\n" if ref($hh{'QUESTION_TEXT'}) eq 'HASH';

-stevieb

Replies are listed 'Best First'.
Re^4: how to identify a null hash value
by smartyollie (Novice) on Jun 04, 2015 at 21:32 UTC
    I see you are saying it's defined, but I want to check if it contains any data - has a non null value. The dumper output shows an empty hash as its value, but I want to print something different if it has an empty hash, vs a non empty hash. That's my else clause - but I can't get that else clause to execute. And note that it is an empty hash, but it doesn't print a null string when I print it - instead, it prints "HASH(xxxx)" string, which I don't want

      Ok, so you want to see if the hash in that value is empty... I think I get you now ;) Try this:

      if (%{$hh{'QUESTION_TEXT'}}){ # do stuff... } else { # it's empty, so do different stuff... }

      It dereferences the inner hashref, and checks if it isn't null (empty).

      -stevieb

        In addition to stevieb's correct answer, I'll add: there's no such thing as "NULL" in Perl, so that may cause some confusion. Values in Perl may be defined or undefined, as well as true or false. But references (pointers to other things) are always defined and true, even if the thing they point to is empty, as in the case of a hash with no keys and values.

        #!/usr/bin/env perl use 5.010; use warnings; use strict; my %hash = (); # create empty hash my $ref = \%hash; # create reference pointing to empty hash if($ref){ say 'Reference is true'; # <- always true } else { say 'Reference is false'; } if (%$ref){ # derefence hash and check the number of elements in it say 'Hash has elements'; } else { say 'Hash is empty'; # <-- hash has no elements } $hash{a} = 1; # add a key and value to hash if (%$ref){ # derefence hash and check the number of elements in it say 'Hash has elements'; # <-- now it has one key and one value } else { say 'Hash is empty'; }

        Aaron B.
        Available for small or large Perl jobs and *nix system administration; see my home node.

        This did not work. This complains under "use strict" rules:

        Can't use string ("Some actual text here"...) as a HASH ref while "strict refs" in use ...

        When I ran without "use strict", it ALWAYS executed the else clause.