how to check if a hash is empty in perl

前端 未结 4 474
孤城傲影
孤城傲影 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-16 09:43

    "Better" is a subjective term. However I would argue that code that is easier to understand can be described as "better". For this reason I conclude that !keys %hash is better, because everybody writing perl code will know what this code does and that it works. !%hash is something at least I would have to look up to ensure if it really works or only looks like it would work. (The reason being that the return value of a hash in scalar context is rather confusing while an arrays behavior in scalar context is well known and often used.)

    Also, !keys %hash is safe.

    So no, there is no better or safer way to check if a hash is empty.

提交回复
热议问题