Hash in Perl adds key if it does not exist

后端 未结 1 1427
清酒与你
清酒与你 2021-01-21 03:18

I have the following perl script which is storing some details in a hash. After populating some entries in the hash, I\'m printing the content of the hash which produces the fol

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-21 03:56

    This is called autovivification. It is a feature of Perl that allows you to use a hash element that you haven't previously declared or initialized. It occurs whenever an undefined value (like $components{'11:Name11'}) is dereferenced (which happens when Perl tries to evaluate $components{'11:Name11'}{'name'}).

    There is a autovivification pragma that you can unuse to disable this behavior.

    {
        no autovivification;
        if ($hash{"non-existent-key"}{"foo"}) {  # won't create $hash{"non-existent-key"}
        ...
    }
    

    0 讨论(0)
提交回复
热议问题