raybies has asked for the wisdom of the Perl Monks concerning the following question:

I allocated a hash, but didn't define any elements, and wanted to see if I had any elements in it. So I did...
my %hash; ... #check to see if anything's in my hash... if (defined %hash) ...
and this yielded a warning saying this was deprecated. So Is the "acceptable" way to see if there's any elements in my hash just to do:
my %hash; ... #check to see if anything's in my hash... if (%hash) ...
It works fine. And it doesn't yield a warning. Just was curious... --Ray

Replies are listed 'Best First'.
Re: if (defined %hash) deprecated
by Athanasius (Bishop) on Oct 15, 2012 at 16:08 UTC

    Yes. From defined:

    Use of defined on aggregates (hashes and arrays) is deprecated. It used to report whether memory for that aggregate had ever been allocated. This behavior may disappear in future versions of Perl. You should instead use a simple test for size:
    if (@an_array) { print "has array elements\n" } if (%a_hash) { print "has hash members\n" }

    Hope that helps,

    Athanasius <°(((><contra mundum

Re: if (defined %hash) deprecated
by Rudolf (Pilgrim) on Oct 15, 2012 at 16:13 UTC

    This is definetly one of those things that I aswell have wondered about. I've been forced to search the hash to see if any items where inside (or check it's buckets by assigning a scalar). Knowing that (%hash) acts like it should is a nice tidbit! thanks for the post.

      By assigning to a scalar or by checking truthiness, you’re forcing a scalar context, so it can be expected to behave the same – that is, return a falsy value (0) when empty and non-falsy when not (and all the bucket counts are non-falsy). Same goes for arrays which report number of elements when not wantarray.