Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

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

Comment on if (defined %hash) deprecated
Select or Download Code
Re: if (defined %hash) deprecated
by Athanasius (Monsignor) 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 (Monk) 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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://999110]
Approved by dorko
Front-paged by Tanktalus
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (2)
As of 2014-09-20 17:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (160 votes), past polls