in reply to One to many hash question

foreach my $type ( keys %sandwichHash ) { print "Sandwich $type\n" if $sandwichHash{$type} eq 'burger'; }

Replies are listed 'Best First'.
Re^2: One to many hash question
by BengalsRock (Initiate) on May 06, 2008 at 18:43 UTC
    Thanks, I was just hoping that there was some way to get information if exists returned more than one value without having to traverse the hash for every comparison....

    Writing code is an artform

      You can't, unless you create a reverse lookup as dragonchild suggests. Consider:

      use strict; use warnings; use Data::Dump::Streamer; my %hash = ( doubleCheeseBurger => 'burger', cheeseBurger => 'burger', cheeseSandwich => 'sandwich', tomatoSandwich => 'sandwich', ); my %rHash; push @{$rHash{$hash{$_}}}, $_ for keys %hash; Dump (\%hash, \%rHash);

      Prints:

      $HASH1 = { cheeseBurger => 'burger', cheeseSandwich => 'sandwich', doubleCheeseBurger => 'burger', tomatoSandwich => 'sandwich' }; $HASH2 = { burger => [ 'cheeseBurger', 'doubleCheeseBurger' ], sandwich => [ 'cheeseSandwich', 'tomatoSandwich' ] };

      Note that the reverse lookup hash has a list of entries for each key because of the many to one mappings in the original hash.


      Perl is environmentally friendly - it saves trees