how to check if a hash is empty in perl

前端 未结 4 470
孤城傲影
孤城傲影 2020-12-16 08:57

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

if (!keys %hash) { print \"Empty\";} 
4条回答
  •  遥遥无期
    2020-12-16 09:41

    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)

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

提交回复
热议问题