mercredi 12 août 2020

What's the difference between these two writing style of Perl if, why are the result different?

I have write these two, but they got different result. I am not sure where is wrong.

For the first style, I put the operation before " if " condition:

$da{$array[0]}++ and $str="\n$array[0]\t$array[1]\t$array[-2]\n" if(exists $da{$array[0]} and $str!~/$array[0]\t$array[1]\t$array[-2]/);

and the result is:
R8112033 3
R8112038 1
R8112056 1
R8112057 1

while for the second common style:

if(exists $da{$array[0]} and $str!~/$array[0]\t$array[1]\t$array[-2]/)
  {
    $da{$array[0]}++;
    $str="\n$array[0]\t$array[1]\t$array[-2]\n";
  }

the result is:
R8112033 2
R8112038 1
R8112056 1
R8112057 1

The second result is what I want, but I don't know why it won't work in the first style.

Here is the data file:
R8112033 EGFR T790M missense_mutation No
R8112033 EGFR L858R missense_mutation No
R8112033 TP53 - missense_mutation No
R8112038 KRAS G12D missense_mutation No
R8112056 - L858R missense_mutation Yes
R8112057 KRAS G12C missense_mutation No

Here is the full code:

use strict;
use warnings;

my $infile=shift;
my %da;
my $str=0;
open IN, "$infile" or die $!;
while(<IN>)
{
        s/\r|\n//g;
        my @array = split /\t/,$_;
        $da{$array[0]}=0 if($array[-3]=~/\w/);
}
close IN;

open IN, "$infile" or die $!;
while(<IN>)
{
        s/\r|\n//g;
        my @array = split /\t/,$_;
        $da{$array[0]}++ and $str="\n$array[0]\t$array[1]\t$array[-2]\n" if(exists $da{$array[0]} and $str!~/$array[0]\t$array[1]\t$array[-2]/);
        #if(exists $da{$array[0]} and $str!~/$array[0]\t$array[1]\t$array[-2]/)
        #{
        #        $da{$array[0]}++;
        #        $str="\n$array[0]\t$array[1]\t$array[-2]\n";
        #}
}
close IN;

for my $key (sort keys %da)
{
        print "$key\t$da{$key}\n";
}

Any help is appreciated.

Aucun commentaire:

Enregistrer un commentaire