in reply to Using an element in a Hash of Arrays to access the key

#!/usr/bin/perl # http://perlmonks.org/?node_id=1185923 use strict; use warnings; my @array1 = ("one", "two", "three", "four", "five"); my @array2 = ("banana", "pear", "apple"); my %hash = ( numbers => \@array1, fruit => \@array2 ); # make a reverse lookup hash my %reverse; for my $key (keys %hash) { push @{ $reverse{$_} }, $key for @{ $hash{$key} }; } # then do direct lookup ( you may get multiple values, or none ) print "banana -> @{ $reverse{'banana'} // [] }\n";

Replies are listed 'Best First'.
Re^2: Using an element in a Hash of Arrays to access the key
by orangepeel1 (Novice) on Mar 25, 2017 at 17:45 UTC
    Thank you, this worked. Could you clarify what the purpose of  // [] is in  print "banana -> @{ $reverse{'banana'} // [] }\n";?

      That is there to handle the case when the element you are trying to look up does not exist.
      Try looking up 'peach' with and without that part of the code.