how to check if a hash is empty in perl

if (%hash)

Will work just fine.

From perldoc perldata:

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


There was a bug which caused tied hashes in scalar context to always return false. The bug was fixed in 5.8.5. If you're concerned with backwards compatibility that far back I would stick with if( !keys %hash ). Otherwise use if( !%hash ) as recommended by others.


Simpler:

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

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

  • false if there are zero keys (not defined in the documentation but experimentally returns 0)

Depending on the version of Perl, either of the following:

  • A string signifying how many used/allocated buckets are used for >0 keys, which will of course be NOT false (e.g. "3/6"). (Non-empty string evaluate to true)

  • The number of keys in the hash (as explained in perldata: "As of Perl 5.25 the return was changed to be the count of keys in the hash. If you need access to the old behavior you can use "Hash::Util::bucket_ratio()" instead.")