Megiddo Megiddo - 2 months ago 11
Perl Question

Perl: extracting certain values from matrix file

Given a matrix like text file, I want to extract all the lines (

\t
is the separator) that contain values > 60 in the 3`rd column (pos 2) and values > 80 in the 6 th (pos 5) and send the output to a different file.So far I got:

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

open(my $in, "file.txt")or die $!;
my $line = <$in>;
my $count;
while (<$in>) {
chomp;
my @element = split (/\t/,$_);
if ($element[2] >= 60 && $element[5] > 80){
$count++;
}
}
close $in;
print $count;


What is wrong? Thanks.PS. I have found similar questions but my low level Perl skills prevented me from extracting resolve.

Answer
  1. You forgot to add read mode (<) in open.
  2. Make sure the lines in your file are really tab separated.

Below worked fine for me.

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

open(my $in, "<", "file.txt") or die $!;

my $count;

while (<$in>) {
   chomp;
   my @element = split (/\t/,$_);
   if ($element[2] >= 60 && $element[5] > 80){
       $count++; 
   }
}

close $in;
print $count;

Where file.txt

10  20  60  40  50  90  70  80
10  20  20  40  50  30  70  80
10  20  40  40  50  50  70  80
10  20  65  40  50  80  70  80
10  20  70  40  50  90  70  80
10  20  50  40  50  90  70  80

i.e. first and fifth lines of file satisfied the if condition.

Comments