in reply to How to match specific elements of multiple array_references
#!/usr/bin/perl use warnings; use strict; use Data::Dumper; my @array1 = ( ["a", "b", "match"], ["c", "d", "e"], ["f", "g", "h"], ["i", "j", "k"], ); my @array2 = ( ["l", "m", "z"], ["n", "o", "p"], ["q", "r", "s"], ["t", "u", "match"], ); # Pass in data structures and define # which element to match against. my($matched1, $matched2) = common_lists(\@array1, \@array2, 2); print Data::Dumper->Dump([$matched1, $matched2], ["matched1", "matched +2"]); # Find the common lists where element $element_to_match matches. # Result should return both lists that have "match" # in their third element. sub common_lists { #don't mix camel-case and underscored words randomly my ($array_ref1, $array_ref2, $element_to_match) = @_; my(%index_first, $key, $array2); # For this, we build a hash of the elements to match from the firs +t # array of arrays. $index_first{${$$array_ref1[$_]}[$element_to_match]} = $_ for 0 .. @$array_ref1 - 1; # Then we iterate on the second array of arrays, for $array2 (@$array_ref2) { # extract the key from it, $key = $$array2[$element_to_match]; # check if that key is in the hash we've built, and if so exists($index_first{$key}) and # we return the corresponding array from the first array o +f arrays, # and the one from the second array of arrays as well. return $$array_ref1[$index_first{$key}], $array2; } } __END__
Sorry, but I've adjusted your code a bit to my style.
Output is:
$matched1 = [ 'a', 'b', 'match' ]; $matched2 = [ 't', 'u', 'match' ];
|
|---|