in reply to Re^4: Compare three columns of one file with three columns of another file in perl
in thread Compare three columns of one file with three columns of another file in perl

Hi Thanks.Below is the code i tried but it does not print anything to the STDOUT.

#!usr/bin/perl use strict; use warnings; my ($infile1,$infile2) = @ARGV; open (IFILE1, "<", $infile1) || die "Cannot open $infile1 +:$!\n"; open (IFILE2, "<", $infile2) || die "Cannot open $infile2:$!\n"; my @array1; my %hash1; my $str; while (<IFILE1>) { @array1 = split (" ", $_); $str = $array1[0]."\t".$array1[1]."\t".$array1[2]; $hash1{$str} = 1; } close IFILE1; my @array2; my $string; while (<IFILE2>) { @array2 = split (" ", $_); $string = $array2[0]."\t".$array2[3]."\t".$array2[4]; #print "$string\n"; if (exists($hash1{$string})) { print "$string\n"; } } close IFILE2;
  • Comment on Re^5: Compare three columns of one file with three columns of another file in perl
  • Download Code

Replies are listed 'Best First'.
Re^6: Compare three columns of one file with three columns of another file in perl
by anonym (Acolyte) on May 26, 2015 at 05:04 UTC

    Hey thanks.The code i sent works with the other pair of input files. I guess there is no line common between file1.txt and file2.txt that is why it does not print anything.

      You're welcome, you did a good job of turning my pseudo-code into working code!

      One suggestion: don't create variables outside a loop if they're only used within the loop. So your @array1 can be instantiated inside your first loop, like this:

      my @array1 = split (" ", $_);

      Same thing with @array2, $str, and $string. The way you're doing it will work, but it may introduce bugs in more complicated code, because those variables will continue to exist after those loops are finished, and could conflict with other uses elsewhere. It's best to keep variables inside as small a context as possible, so only create them outside a loop if you need them to continue to exist after the loop is finished.

      Aaron B.
      Available for small or large Perl jobs and *nix system administration; see my home node.

        Thanks Aaron for your suggestions and help. Thanks so much.