Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

if (defined %hash) deprecated

by raybies (Chaplain)
on Oct 15, 2012 at 16:01 UTC ( #999110=perlquestion: print w/replies, xml ) Need Help??
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 (Chancellor) 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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://999110]
Approved by dorko
Front-paged by Tanktalus
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (5)
As of 2017-05-29 12:00 GMT
Find Nodes?
    Voting Booth?