Hi Perlmonks,

This post is bit of follow up to my previous post. I got a refined code from Marshall and it worked fine. But, now I am using the same code in another file which has several repeat IDs. I want to match this with another file which is a subset of the first file. Though, I was able to get the result, because of the repeat IDs, my output has less number of rows than the first file. How can I tweak the code below to resolve this repeat IDs.

#!/usr/bin/perl -w use strict; use warnings; use Text::CSV_XS; open (my $FILE1, '<', "File1.csv") or die "cannot open file1 $!\n"; open (my $FILE2, '<', "File2.csv") or die "cannot open file3 $!\n"; open (my $FILE3, '>', "OutputFile.csv") or die "cannot open file3 $!\n +"; my $csv = Text::CSV_XS->new ({ binary => 1, eol => $/ , sep_char => "\t", always_quote =>1}); print $FILE3 "Match\t".<$FILE1>; # header for file3 <$FILE2>; # skip header line of file2 my %file1; my %file2; while (my $row = $csv->getline($FILE1)) { chomp $row; my @fields = @$row; my $id = $fields[1]; my $newfield=["",@fields]; if (exists($file1{$id})){ print "repeat $id\n"; } $file1{$id}=$newfield; } while (my $row = $csv->getline($FILE2)) { chomp $row; my @fields = @$row; my $id = $fields[0]; $file2{$id}=["","",@fields,"","","","","","","","","","","","","", +"","",""]; } foreach my $id1 (keys %file1) { if (exists $file2{$id1}) { $file1{$id1}[0] ="HK"; #both files $csv->print ($FILE3, $file1{$id1}); } else { $file1{$id1}[0] ="NOT_HK"; #file1 only $csv->print ($FILE3, $file1{$id1}); } }

In reply to Matching two files based on one column common in each by bluray

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.