I have an array of key names and need to remove any keys that are not in this list from a hash.
I gather deleting keys in a hash is a Bad Thing while iterating over it, but it does seem to work:
use strict;
use warnings;
use Data::Dumper;
my @array=('item1', 'item3');
my %hash=(item1 => 'test 1', item2 => 'test 2', items3 => 'test 3', item4 => 'test 4');
print(Dumper(\%hash));
foreach (keys %hash)
{
delete $hash{$_} unless $_ ~~ @array;
}
print(Dumper(\%hash));
gives the output:
$VAR1 = {
'item3' => 'test 3',
'item1' => 'test 1',
'item2' => 'test 2',
'item4' => 'test 4'
};
$VAR1 = {
'item3' => 'test 3',
'item1' => 'test 1'
};
What is a better/cleaner/safer way of doing this?