How should I delete hash elements while iterating?

前端 未结 4 913
醉话见心
醉话见心 2021-01-11 11:50

I have fairly large hash (some 10M keys) and I would like to delete some elements from it.

I usually don\'t like to use delete or splice, a

4条回答
  •  孤独总比滥情好
    2021-01-11 12:46

    I recommend doing two passes because it's more robust. Hash order is effectively random, so there are no guarantees that you'll see the "primary" keys before the related ones. For example, if should_be_deleted() only detects the primary keys that aren't wanted and the related ones are calculated, you could end up processing unwanted data. A two-pass approach avoids this issue.

    my @unwanted;
    foreach my $key (keys %hash) {
        if (should_be_deleted($key)) {
             push @unwanted, $key;
             # push any related keys onto @unwanted
        }
    }
    
    delete @hash{@unwanted};
    
    foreach my $key (keys %hash) {
        # do something
    }
    

提交回复
热议问题