2

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Always use strict; use warnings;. Add use v5.10; since Perl's (v5.10+) smart matching will be used to compare arrays. Do the following:

my ($match) = grep { @{$aa{$_}} ~~ @$array_ref } keys %aa;

The smart operator ~~ is used here to compare the arrays.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.