#!/usr/bin/perl -w use strict; use warnings; use Text::CSV_XS; open (my $FILE1, '<', "fileX.csv") or die "cannot open file1 $!\n"; open (my $FILE2, '<', "fileY.csv") or die "cannot open file2 $!\n"; open (my $FILE3, '<', "fileZ.csv") or die "cannot open file3 $!\n"; open (my $FILE4, '>', "Outputfile.csv") or die "cannot open file4 $!\n"; my $csv = Text::CSV_XS->new ({ binary => 1, eol => $/ , sep_char => "\t", always_quote =>1}); print $FILE4 "".<$FILE1>; <$FILE2>; <$FILE3>; my %file2; while (my $row = $csv->getline($FILE2)) { my @fields = @$row; my $id = $fields[0]; $file2{$id}=["",@fields]; } my %file3; while (my $row = $csv->getline($FILE3)) { my @fields = @$row; my $id = $fields[0]; $file3{$id}=["",@fields]; } while (my $row=$csv->getline($FILE1)) { my @fields=@$row; @fields=@fields[map{$_}(0..4)]; my $id=$fields[0]; if (exists $file2{$id}) { if(exists $file3{$id}) { my $fields_ref=\@fields; $csv->print ($FILE4,$fields_ref); } else { } } else { } }