in reply to How to test for empty hash?

This works for me:
my %hash = (); # empty hash print "empty!" unless (%hash);
However, this does print -1:
my @a = keys(%hash) print "$#a\n";
So maybe your hash isn't actually empty?

Replies are listed 'Best First'.
Re^2: How to test for empty hash?
by LanX (Saint) on Aug 05, 2021 at 20:25 UTC
    > This works for me:

    And it's well documented defined in perldata (tho hard to find)

    The exact value is only version dependent if the hash is not empty, but still guaranteed to be true (unless tied to magic behaviour)

    Maybe not relevant for the OP but IMHO still of interest to people used to the old behaviour.

      If you evaluate a hash in scalar context, it returns a false value if the hash is empty. If there are any key/value pairs, it returns a true value. A more precise definition is version dependent.

      Prior to Perl 5.25 the value returned was a string consisting of the number of used buckets and the number of allocated buckets, separated by a slash. This is pretty much useful only to find out whether Perl's internal hashing algorithm is performing poorly on your data set. For example, you stick 10,000 things in a hash, but evaluating %HASH in scalar context reveals "1/16", which means only one out of sixteen buckets has been touched, and presumably contains all 10,000 of your items. This isn't supposed to happen.

      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.

      If a tied hash is evaluated in scalar context, the SCALAR method is called (with a fallback to FIRSTKEY).

    > So maybe your hash isn't actually empty?

    Or tied?

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery

Re^2: How to test for empty hash?
by ikegami (Patriarch) on Aug 06, 2021 at 09:37 UTC

    Tip: Hashes are created empty, so = () is useless noise.

    Seeking work! You can reach me at ikegami@adaelis.com