cooldood3490 cooldood3490 - 3 months ago 10
Perl Question

Perl - Hash of Array: Key look-up by Value

I have a hash of arrays (HoA). I have been processing the values of this HoA using

$arrayrefs
. However, now I need to retrieve the
$key
based on the
$arrayrefs
.

my %a = ( 1 => "ONE" ,
2 => "TWO" ,
3 => " Three", );

my %aa = ( 4 => [ 'ONE' , 'TWO', 'THREE'],
5 => ['one' , 'two', 'three'],
6 => ['more', 'dos', 'some'],
);

my @array = ('ONE' , 'TWO', 'THREE');
my $array_ref = \@array;

# returns the $key where the $value is 'ONE'
my ($any_match) = grep { $a{$_} eq 'ONE' } keys %a;
print $any_match."\n"; # this returns '1', as expected.. Good!

my ($match) = grep { $aa{$_} eq @$array_ref } keys %aa;
print $match."\n"; # <--- error: says that match is uninitialized


In the last
print
statement, I would like it to return 4. Does anyone know how to do this?

Answer

You can't compare arrays with eq. A simple solution is to turn both arrays into strings and comparing the strings using eq:

my ($match) = grep { join("", @{$aa{$_}}) eq join("", @$array_ref) } keys %aa;

For comparing arrays you could also utilize one of many modules from CPAN, e.g. Array::Compare, List::Compare, etc.