Reputation: 1691
I have some code as follows. I am trying to search through the hash and if I come across a value that is zero, I want to delete the whole key/value element.
my %hashy = (
a => my $a,
b => my $b,
c => my $c,
d => my $d,
e => my $e
);
$hashy{'a'} = 0;
$hashy{'b'} = 1;
$hashy{'c'} = 0;
$hashy{'d'} = 2;
$hashy{'e'} = 1;
my @keys = keys %hashy;
my @values = values %hashy;
my $ind = 0;
foreach my $v (@values) {
delete $hashy{$keys[$ind]} if ($v == 0);
}
So the expected output of printing %hashy
would be: b1d2e1
(ignoring order of elements)
At the moment I get: c0a0b1d2
which isn't even close... any help would be appreciated :)
Upvotes: 2
Views: 173
Reputation: 50328
Another way to do it:
delete @hash{ grep $hash{$_} == 0, keys %hash };
Upvotes: 3
Reputation: 339786
Iterating over the values won't help because you lose the association between the values and the keys, although I guess that's what $ind
was supposed to be helping you track.
Just iterate over the keys instead:
foreach my $k (keys %hashy) {
delete $hashy{$k} if ($hashy{$k} == 0);
}
Upvotes: 6