SPUG: Slice of HashOfHash

John Costello cos at indeterminate.net
Wed Nov 15 16:32:55 PST 2006


On Wed, 15 Nov 2006 Eric.D.Peterson at alltel.com wrote:

> Given a Hash of a Hash is it possible to make a slice (I presume this
> will be another hash) of a subset of the HoH based upon a value, not the
> key?  For example:
> 
> my %HoH = (
>     flintstones => 
>     {
>         husband   => "fred",
>         pal       => "barney",
>     },
>     jetsons => 
>     {
>         husband   => "george",
>         wife      => "jane",
>         "his boy" => "elroy",  # Key quotes needed.
>     },
>     jones => 
>     {
>         husband   => "fred",
>         wife       => "linda",
>     },
>     simpsons => 
>     {
>         husband   => "homer",
>         wife      => "marge",
>         kid       => "bart",
>     }
> );
> 
> 
> How can I make a new hash  or loop through this HoH where husband =
> "fred"?  
> 
> I've been reading up on slices and printing hashes, but I can't seem to
> find an example or description on playing with HoH subsets.  I've tried
> looping through the full HoH and adding those desired elements to a new
> HoH but that seems awkward and not quite right & cumbersome.  So I
> thought I'd ask ya'll for some help.


For looping, you could do the following

OUTER: foreach my $key (keys %HoH) {
	INNER: foreach my $innerkey (keys % { $HoH{$key} }) {
		if ($HoH{$key}{$innerkey}{'husband'} eq 'fred') {
			print "Wilma!\n";
		}
	}
}

John



More information about the spug-list mailing list