rsennat has asked for the wisdom of the Perl Monks concerning the following question:

hi all,

i have an hash like this,
Testcase => {'comp' => {'cmd' => {'tc1' => {platform_type => 'all', testsuite_type => 'all', view => 'private'}, 'tc2' => {platform_type => 'all', testsuite_type => 'all', view => 'private'} } } }
I delete a key/ value pair in the hash like this,
delete $hoh{$comp}{$cmd}{$tc1};
But when the value for a key becomes empty, i need to delete that also. How do i delete the key also?
After deleting both 'tc1' and 'tc2' key/value pair, the hash looks like,
Testcase => {'comp' => {'cmd' => {} } }
But actually for "cmd", value is empty. So I would like to remove that. And obviously, "comp" value is also empty, so that also needs to be removed.

thanks
rsennat

Replies are listed 'Best First'.
Re: complete deletion from hash
by wfsp (Abbot) on Nov 24, 2005 at 10:39 UTC

    You could use the keys function to test for the existance of any keys.

    #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $h = { 'comp' => { 'cmd' => { 'tc1' => { platform_type => 'all', testsuite_type => 'all', view => 'private' }, 'tc2' => { platform_type => 'all', testsuite_type => 'all', view => 'private'} } } }; delete $h->{comp}{cmd}{tc1}; delete $h->{comp}{cmd}{tc2}; unless (keys %{$h->{comp}{cmd}}){ delete $h->{comp}{cmd}; } unless (keys %{$h->{comp}}){ delete $h->{comp}; } print Dumper($h); __DATA__ ---------- Capture Output ---------- > "c:\perl\bin\perl.exe" _new.pl $VAR1 = {}; > Terminated with exit code 0.

      The following worked in scalar context without using keys to give list context. An empty hash gives 0 in scalar context.
      delete $hoh{Testcase}{comp}{cmd} unless %{$hoh{Testcase}{comp}{cmd}}; delete $hoh{Testcase}{comp} unless %{$hoh{Testcase}{comp}};
      oh. thats gr8!!!
      thanks a lot
Re: complete deletion from hash
by Perl Mouse (Chaplain) on Nov 24, 2005 at 10:54 UTC
    Here's a recursive sub that does that:
    sub rec_del; sub rec_del { my ($hash, @keys) = @_; return unless @keys; my $key = shift @keys; return unless exists $$hash{$key}; if (@keys) { rec_del $$hash{$key}, @keys; delete $$hash{$key} unless %{$$hash{$key}}; } else { delete $$hash{$key} } }
    Call it as rec_del $hoh, $comp, $cmd, $tc1.
    Perl --((8:>*