Search code examples
perlperl-data-structures

Delete value from Perl hash of arrays of hashes


I'm trying to delete values from a hash of arrays of hashes that I created with the following code:

while ((my $Genotype1, my $Fitness1) = each (%Normalisedfithash)) {
  while ((my $Parent1A, my $TallyP1) = each(%P1Tallyhash)) {
    my $ParentTally = 0;
    my $SecondParent = {
      Parent2 => $Parent1A,
      Tally => $ParentTally,
    };
    push @{ $StoredParentshash{$Genotype1}}, $SecondParent;

I have been trying to delete values from %StoredParentshash where Tally is zero. (I have further code which updates Tally, but some are not updated and I want them removed from the hash).

I have written the following:

for my $Parent (keys %StoredParentshash) {
  my $aref1 = $StoredParentshash{$Parent};
  for my $hashref1 (@$aref1) {
    my $Tally =  $hashref1->{'Tally'};
    if ($Tally == 0){
      delete $hashref1->{'Tally'};
      delete $hashref1->{'Parent2'};
    }
  }
}

This code sort of deletes the data, but when I use Data::Dumper the structure I get back looks like this:

 '7412' => [
        {},
        {
          'Tally' => 1,
          'Parent2' => '2136'
        },
        {},
        {},
        {},

How can I completely remove the keys where the Tally is zero rather than being left with {}?

Thanks!


Solution

  • The code that you say has generated the data structure is faulty, as it is missing two closing braces.

    You must show either your actual code with balanced { .. } or a dump of %StoredParentshash before we can help you properly.

    If Tally and Parent2 are the only keys in the SecondParent hashes, then you should write something like

    for my $children (values %StoredParentshash) {
      @$children = grep $_->{Tally} != 0, @$children;
    }