dgBP
dgBP

Reputation: 1691

Search through hash, if value is zero delete it

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

Answers (2)

Ilmari Karonen
Ilmari Karonen

Reputation: 50328

Another way to do it:

delete @hash{ grep $hash{$_} == 0, keys %hash };

Upvotes: 3

Alnitak
Alnitak

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

Related Questions