user1385055
user1385055

Reputation: 21

Matching three columns of one file with three columns of another file in perl

I am trying to match 3 columns of one file( first three columns) with three columns 0,3,4 of second file. I am having problem with the code below:Please help me.Thanks.

#!usr/bin/perl
  use strict;
  use warnings;

  my $infile1 = $ARGV[0];
  my $infile2 = $ARGV[1];
  my $outfile = $ARGV[2];

  open (INFILE1,"<", $infile1) || die "Cannot open $infile1:$!\n";
  open (INFILE2, "<", $infile2) || die "Cannot open $infile2:$!\n";
  open (OUTFILE, ">", $outfile) || die "Cannot open $outfile:$!\n";

  my @array1;
  my @array2;
  my @array3;
  my @array4;
  my $_;
  while (<INFILE1>) {
      chomp;
      @array1 = split (' ', $_);
      push (@array2, "@array1\n");
      #print "@array2\n";
  }
  while (<INFILE2>) {
      chomp;
      @array3 = split (' ', $_);
      push (@array4, "@array3\n");
      #print "@array4\n";
  }
  #print "@array2\n";
  #print "@array4\n";
  foreach my $array2(@array2) {
       my @line = split(/\s+/,$array2);
       my $chr1 = $line[0];
       my $start1 = $line[1];
       my $end1 = $line[2];
       #print "$line[0]\n";
  foreach my $array4(@array4) {
       my @values = split(/\s+/, $array4);
       my $chr2 = $values[0];
       my $start2 = $values[3];
       my $end2 = $values[4];
      if (($chr1 eq $chr2) && ($start1 eq $start2) && ($end1 eq $end2)) {
         #print  "$start2\n";
         print  "$chr2\t$start2\t$end2\n";
       }
   }
 }

file1.txt few lines are as below:

chr10   40095550        40096075
chr10   40102275        40102575
chr10   40139575        40140100

file2.txt few lines are as below:

chr1    mm10_knownGene  exon    3205904 3207317 0.000000        -       .       gene_id "uc007aet.1"; transcript_id "uc007aet.1"; 
chr1    mm10_knownGene  exon    3213439 3215632 0.000000        -       .       gene_id "uc007aet.1"; transcript_id "uc007aet.1"; 
chr1    mm10_knownGene  stop_codon      3216022 3216024 0.000000        -       .       gene_id "uc007aeu.1"; transcript_id "uc007aeu.1"; 

Upvotes: 0

Views: 79

Answers (1)

Sobrique
Sobrique

Reputation: 53478

The solution to your problem here is read perldata and have a look at the section on hashes. These are associative arrays, of key-value pairs.

It makes the vast majority of your code redundant.

my %exists; 

while ( <INFILE1> ) {
     my ( $chr, $firstnum, $secondnum) = split; 
     $exists{$chr}{$firstnum}{$secondnum}++; 
}

while ( <INFILE2> ) {
    my ( $chr, $mm, $thing, $firstnum, $secondnum ) = split;
    print if $exists{$chr}{$firstnum}{$secondnum}; 
}

I would also suggest that you use 3 argument open with lexical file handles instead.

e.g. :

 open ( my $infile1_fh, "<", $infile1 ) or die $!;

and then

 while ( <$infile1_fh> ) {

Because then they're locally scoped rather than globals.

Upvotes: 1

Related Questions