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
Based on the example in the question, you could use a grep
to filter out the keys that match your $key
token.
Update
Your comment has clarified your need. My suggestion would be to determine the indexes that match your requirement and update you @keys
set accordingly. The idea is to update @keys
while looping over it so that unnecessary iterations are avoided.
I've implemented the simple grep as a customizable function here.
sub matches { $_[0] =~ /$_[1]/ ? 1 : 0 } # Simple grep implemented here
my @keys = keys %hash; # @keys should initially contain all keys
while ( @keys ) {
my $key = shift @keys;
next unless should_be_deleted ($key); # Skip keys that are wanted
my @indexes_to_delete = grep { matches ($key, qr/$keys[$_]/) } 0 .. $#keys;
delete @hash { @keys[@indexes_to_delete] }; # Remove the unwanted keys
splice @keys, $_, 1 foreach @indexes_to_delete; # Removes deleted ...
# ... elements from @keys.
# Avoids needless iterations.
}