How to check if a hash is empty in perl

I use the following code to check if the hash is empty. Is there a better way and is it safe to use?

if (!keys %hash) { print "Empty";} 
+44
perl hash
Feb 25 2018-12-12T00:
source share
4 answers
 if (%hash) 

Will work fine.

From perldoc perldata :

If you evaluate the hash in a scalar context, it returns false if the hash is empty. If there are key / value pairs, it returns true; More precisely, the return value is a string consisting of the number of buckets used and the number of buckets allocated, separated by a slash.

+76
Feb 25 2018-12-12T00:
source share

There was an error due to which bound hashes in a scalar context always returned false. The error was fixed in 5.8.5 . If you are concerned about backward compatibility, then I would stick with if( !keys %hash ) . Otherwise, use if( !%hash ) as recommended by others.

+20
Feb 25 '12 at 21:30
source share

Simpler:

 if (!%hash) { print "Empty"; } 

! imposes a scalar context, and a hash calculated in a scalar context returns:

  • false if there are null keys (not specified in the documentation, but experimentally returns 0

  • A string indicating how many used / allocated buckets are used for keys> 0, which, of course, will NOT be false (for example, "3/6")

+17
Feb 25 2018-12-12T00:
source share

β€œBetter” is a subjective term. However, I would say that code that is easier to understand can be described as "better." For this reason, I came to the conclusion that !keys %hash better, because everyone who wrote the perl code will know what this code does and what it works. !%hash is something, at least I'll have to look to make sure it really works or just looks like it will work. (The reason is that the return value of the hash in the scalar context is rather confusing, while the behavior of arrays in the scalar context is well known and often used.)

In addition !keys %hash preserved.

No, there is no better or safer way to check if the hash is empty.

+1
Apr 14 '17 at 19:14
source share



All Articles