upendra
upendra

Reputation: 2189

how to compare different rows with in the same column in perl

I have file with different columns and i want to parse them first to columns and then take a particular column and compare different rows within that column. Here is my example input file

A02     2260333 2260527 Contig1000|m.2597       216     -
A02     2260222 2260254 Contig1000|m.2597       2       -
A02     2260333 2260528 Contig1000|m.2596       216     -
A02     2261298 2261445 Contig1000|m.2596       202     -
A02     2260845 2260895 Contig1000|m.2596       20      -
A06     1006786 1006986 Contig1002|m.2601       212     -

I have so far parsed the the file and then got the columns. Now i want to take id column and check the different rows with in that id column and compare to see if the first row is same or not. If it is same then i do something and if not do something else.

So far i have written this...

open(my $fh_in, "<", "test_parsing.bed") or die "Could not open file $!";

while(my $line = <$fh_in>) {
    chomp($line);
    my ($chr, $start, $end, $id, $map, $strand) = split ' ', $line;     
    print Dumper($id);

}   
close $fh_in;

Here is the output file that I wanted to generate....

A02      2260222 2260895 Contig1000 216 - 2260222 2260895 0 3 33,196,50 0,111,623

and then do the same for id Contig1000|m.2596 and so on......

Thanks

Upendra

Upvotes: 0

Views: 389

Answers (1)

Borodin
Borodin

Reputation: 126722

I would write something like this

use strict;
use warnings;

open my $fh_in, '<', 'test_parsing.bed' or die "Could not open input file: $!";

my $first_id;

while (<$fh_in>) {
  my ($chr, $start, $end, $id, $map, $strand) = split;

  if (not defined $first_id) {
    $first_id = $id;
  }
  elsif ($id eq $first_id) {
    # Action in case ID matches first line
  }
  else {
    # Action in case ID differs from first line
  }
}

Upvotes: 1

Related Questions