How can I check if a key exists in a deep Perl hash?

后端 未结 5 938
渐次进展
渐次进展 2020-12-08 14:43

If I understand correctly, calling if (exists $ref->{A}->{B}->{$key}) { ... } will spring into existence $ref->{A} and $ref->

5条回答
  •  时光取名叫无心
    2020-12-08 14:55

    Check every level for existence before looking at the top level.

    if (exists $ref->{A} and exists $ref->{A}{B} and exists $ref->{A}{B}{$key}) {
    }
    

    If you find that annoying you could always look on CPAN. For instance, there is Hash::NoVivify.

提交回复
热议问题