Search code examples
perlhashperl-data-structures

Deleting each final value in multidimensional hash (perl)


I have a multidimensional hash (the number of dimensions will vary) where every value is either a simple scalar value or a reference to another hash.

Is there a good way to delete each final value, preserving the elements which point to other hashes? Basically, take all the meat off the skeleton.


Solution

  • I suspect there are good modules out there that could help with the problem, probably several, but I always have a hard time choosing one when it comes to traversing data structures in Perl, and the problem isn't super complex to begin with. So here it is done "by hand":

    sub prune {
      my ($href) = @_;
      while (my ($key, $value) = each %$href) {
        if (ref $value eq 'HASH') {
          prune($value);
        } else {
          delete $href->{$key};
        }
      }
    }