#!/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' ];

In reply to Re: How to match specific elements of multiple array_references by ambrus
in thread How to match specific elements of multiple array_references by awohld

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.