Is it safe in Perl to delete a key from a hash reference when I loop on the same hash? And why?

前端 未结 2 576
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-17 14:27

I basically want to do this:

foreach my $key (keys $hash_ref) {

    Do stuff with my $key and $hash_ref

    # Delete the key from the hash
    delete $hash         


        
2条回答
  •  遇见更好的自我
    2021-01-17 14:47

    It is safe, because keys %hash provides entire list once, before you start iterating. foreach then continues to work on this pre-generated list, no matter what you change inside actual hash.

    It eats up your memory though, because you keep entire list until you've done.

提交回复
热议问题