yueli has asked for the wisdom of the Perl Monks concerning the following question:

Hi Two files, if the first line and the first column are the same, print this line, the second line, the third line,the fourth line. What's wrong with me?

01.txt >SR1.2 >SR1.3 02.txt >SR1.1 HWI-ST ATGCTGCT TCGTCGAT CTGATCAGCTAC >SR1.2 HWI-ST0 TTTTGCTGCT TCGTTGGG CTTTATCAGCTAC >SR1.3 HWI-ST0787 GGGGGCTGCT AATCGTCGAT AACTGATCAGCTAC result >SR1.2 HWI-ST0 TTTTGCTGCT TCGTTGGG CTTTATCAGCTAC >SR1.3 HWI-ST0787 GGGGGCTGCT AATCGTCGAT AACTGATCAGCTAC #!/usr/bin/perl -w use strict; open(IN1,"01.txt") || die "Cannot open this file"; my @lines1 = <IN1>; open(IN2,"02.txt") || die "Cannot open this file"; my @lines2 = <IN2>; my $i=0; open(OUT,">out01") || die "Cannot open this file"; for my $item1(@lines1){ chomp $item1; my@tmp1=split(/\s+/, $item1); for my $item2(@lines2){ chomp $item2; my @tmp2=split(/\s+/, $item2); if ($tmp1[0] eq $tmp2[0]){ print OUT $lines2[$i],"\n",$lines2[$i+1],$line +s2[$i+2],$lines2[$i+3]; last; } $i++; } print OUT "\n"; } close(IN1); close(IN2); close(OUT);
Thanks in advance!
  • Comment on Two files, if the first line and the first column are the same, print this line, the second line, the third line,the fourth line.
  • Download Code

Replies are listed 'Best First'.
Re: Two files, if the first line and the first column are the same, print this line, the second line, the third line,the fourth line.
by hdb (Monsignor) on Apr 17, 2015 at 06:18 UTC

    If your task is to select those groups of lines in file 2 where the identifier in the first row of the group is in file 1, you should read file 1 into a hash for easier lookup and then loop over file 2. For example like this:

    use strict; use warnings; # read file 1 into hash, don't forget to chomp; # left as exercise # result should look like this: my %file1 = ( '>SR1.2' => 1, '>SR1.3' => 1, ); # loop over file two while(<DATA>){ next unless /^(>.*?)\s/ and exists $file1{$1}; print $_.<DATA>.<DATA>.<DATA>; } __DATA__ >SR1.1 HWI-ST ATGCTGCT TCGTCGAT CTGATCAGCTAC >SR1.2 HWI-ST0 TTTTGCTGCT TCGTTGGG CTTTATCAGCTAC >SR1.3 HWI-ST0787 GGGGGCTGCT AATCGTCGAT AACTGATCAGCTAC >SR1.4 HWI-ST0787 GGGGGCTGCT AATCGTCGAT AACTGATCAGCTAC
Re: Two files, if the first line and the first column are the same, print this line, the second line, the third line,the fourth line.
by james28909 (Deacon) on Apr 17, 2015 at 04:30 UTC
    01.txt >SR1.2 >SR1.3 02.txt >SR1.1 HWI-ST
    "if the first line and the first column are the same"
    Your first line and the first column arent the same. Thats the problem to begin with, clearly the line you are trying to match is not on the first line of file 2.
Re: Two files, if the first line and the first column are the same, print this line, the second line, the third line,the fourth line.
by vinoth.ree (Monsignor) on Apr 17, 2015 at 05:32 UTC
    Hi,

    Where did you initialize the $i variable in your code?


    All is well. I learn by answering your questions...