SPUG: Slice of HashOfHash

jerry gay jerry.gay at gmail.com
Wed Nov 15 16:32:29 PST 2006


On 11/15/06, John W. Krahn <krahnj at telus.net> wrote:
> 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' ) {
>
probably better not to hardcode here:
  for my $hash ( @HoH{ keys %HoH } ) {
      if ( $hash->{ husband } eq 'fred' ) {

but the if statement is somewhat unsafe. in the case where the subhash
doesn't have a key named 'husband', it will be autovivified. this may
or may not be a problem. if it is, you'll want something more like:
  for my $hash ( @HoH{ keys %HoH } ) {
      if ( exists $hash->{ husband } and $hash->{ husband } eq 'fred' ) {

~jerry


More information about the spug-list mailing list