in reply to Deleting from Hash-of-Hash using references

Here is some code for you...
I like pp in Data::Dump although it is not a core module, it is nice for compact representations of structures.

In order to delete the keys associated with $href1 or $href2 (they are the same), it is necessary to cycle through the keys of %HoH, and compare $href1 against the values of those keys...

#!/usr/bin/perl -w use strict; use Data::Dump qw(pp); use Data::Dumper; my %HoH = ( flintstones => { lead => "fred", pal => "barney", }, jetsons => { lead => "george", wife => "jane", "his boy" => "elroy", }, ); my $href1 = \%{$HoH{flintstones}}; my $href2 = $HoH{flintstones}; my $href3 = \%HoH; #Fails #yes, indeed this will fail!! #delete($href1); #delete($href2); # These are both references to the sub hash of flintstones... # sometimes the ability to omit parens in Perl is good thing # sometime not, here not: print pp ($href1), "\n"; #{ lead => "fred", pal => "barney" } print pp ($href2), "\n"; #{ lead => "fred", pal => "barney" } print "printing HOH...\n"; print pp ($href3), "\n"; #printing HOH... #{ # flintstones => { lead => "fred", pal => "barney" }, # jetsons => { "his boy" => "elroy", lead => "george", wife => "jane" + }, #} foreach my $TV_show (keys %HoH) { delete $HoH{$TV_show} if $HoH{$TV_show} == $href1; } print "printing HOH after the delete... flintstones are gone...\n"; print pp ($href3), "\n"; #printing HOH after the delete... flintstones are gone... #{ # jetsons => { "his boy" => "elroy", lead => "george", wife => "jane" + }, #}
Update: it occurred to me, that perhaps you may want "flintstones" to point to an empty hash. in that case:
change: delete $HoH{$TV_show} if $HoH{$TV_show} == $href1; to: $HoH{$TV_show}={} if $HoH{$TV_show} == $href1;
$HoH{$TV_show}={} means: allocate new hash memory and assign a reference to it to $HoH{$TV_show}

Replies are listed 'Best First'.
Re^2: Deleting from Hash-of-Hash using references
by dol (Novice) on Nov 28, 2011 at 23:12 UTC

    Thanks! Your code makes the distinction very clear.

    I ended up not using references in this case, there was really no need once I rewrote the mess that was my first draft. But it was an interesting lesson that I'm sure will be useful.