SPUG: Slice of HashOfHash
Yitzchak Scott-Thoennes
sthoenna at efn.org
Wed Nov 15 16:53:14 PST 2006
> 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"?
How to loop through, and how to take a slice are two different questions.
If you are looping through, just skip values of the outer hash that don't
match your critera, as others have shown.
If you want a slice, you can make one with an implicit grep loop in the
key list:
@HoH{ grep { $HoH{$_}{'husband'} eq 'fred' } keys %HoH }
but since you typically want to loop over it, it usually makes sense just
to have one explicit loop over all of %HoH instead.
Sometimes it's most convinient to make an array of the keys of interest
and do various things (loops, slices, etc.) with that instead:
@have_husband_fred = grep { $HoH{$_}{'husband'} eq 'fred' } keys %HoH;
More information about the spug-list
mailing list