Greetings to you, oh great Monks

I would like to compare two arrays and keep only those elements that PARTIALLY intersect. For example, let the two array's be:

@arr1 = ("0000007 | John | ABC.txt | 42","0000014 | Jane | XYZ.txt | 34","0000017 | Jessica | GHI.txt | 21", etc);
@arr2 = (0000007, 0000014);
This should result in a text file arr3.dat that contains something like
0000007 | John | ABC.txt | 42
0000014 | Jane | XYZ.txt | 34

I know I should use hashes and know how to split element-by-element but can't figure this one out.

EDIT: CODE ADDED, SORRY FOR BEING UNSPECIFIC. THE FINAL ROW SUGGESTS THAT THE HASHING GOES WRONG...
EDIT AGAIN: SOLUTION BY nemesdani WORKS FINE (BUT SEE MY REPLY).
Thanks!

use feature ':5.10'; open (KEYFILE, "arr2.txt"); @arr2 = <KEYFILE>; close(KEYFILE); # Declare and fill up the hash my %elements; foreach (@arr2) { $elements{$_} = 1; }; #I'm repeating this for several quarterly files: for($year=2006; $year<2012; $year=$year+1){ for($i=1; $i<5; $i=$i+1){ # Load each quarterly file $filea = $year . "QTR" . $i . "arr1.txt"; open(MYINFILE, $filea); @arr1 = <MYINFILE>; close(MYINFILE); $sizegn = @arr1; # For each entry in the quarterly file for($j=0; $j<$sizegn; $j++){ # Pick only lines that contain the string "txt" if($arr1[$j] =~ m/txt/){ # splits the elements of @arr1, and format the first e +lement into 7-digit number: @arraydata = split(/\|/, $arr1[$j]); my $element = sprintf("%07d", $arraydata[0]); # now check if $element is in hash : if (exists $elements{$element}){ open(MYOUTFILE, ">>Arr3.dat"); print MYOUTFILE $arr1[$j]; close(MYOUTFILE); } print "D'oh - '$element' not found\n" unless (exists $ +elements{$element}); } } } }

In reply to Deleting elements of one list using another by Sj03rd

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.