SPUG: Slice of HashOfHash

John W. Krahn krahnj at telus.net
Wed Nov 15 16:26:08 PST 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)

A slice is a list.

> 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"?  

for my $hash ( @HoH{ qw[ flintstones jetsons jones simpsons ] } ) {
    if ( $hash->{ husband } eq 'fred' ) {


Or maybe you just want:

for my $key ( qw[ flintstones jetsons jones simpsons ] ) {
    if ( $HoH{ $key }{ husband } eq '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.

Looping through all 'simpsons' keys would be:

@{ $HoH{ simpsons } }{ qw[ husband wife kid ] }




John
-- 
Perl isn't a toolbox, but a small machine shop where you can special-order
certain sorts of tools at low cost and in short order.       -- Larry Wall


More information about the spug-list mailing list