CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner: Re: [BillKSmith] Help outputting first and last positions of blocks of the same type: Edit Log



Laurent_R
Veteran / Moderator

Aug 25, 2012, 4:06 AM


Views: 3250
Re: [BillKSmith] Help outputting first and last positions of blocks of the same type

Hi

this is a quick try:


Code
use strict;  
use warnings;

#process the first line separatly, this duplicates the code a bit but simplifies the algorithm
my $previous_line = <DATA>;
my $same = 0;
$same = 1 if $previous_line =~ /SAME/;
my $block_start = $1 if $previous_line =~ /^(\d+) /;
my $count = 1;
my $previous_same = $same;

while (my $line = <DATA>) {
$same = 0;
$same = 1 if $line =~ /SAME/;
if ($previous_same != $same or eof) {
#we are at the beginning of a new block, we need first to complete the processing of the previous one
my $block_end = $1 if $previous_line =~ /^(\d+) /;
my $block_type = $previous_same ? "SAME" : "DIFF";
my $output = "$block_start $block_end $count $block_type \n";
print $output;
#reinit of variables
$count = 1;
$block_start = $1 if $line =~ /^(\d+) /;
$previous_same = $same;
}
else {

#we are within in a block; just count
$count ++;
}
$previous_line = $line;
}

__DATA__
1457 G G SAME
1979 G G SAME
2056 T T SAME
3091 A A SAME
3562 A G DIFF
3778 A A SAME
4124 T T SAME
4229 C T DIFF
4571 A G DIFF
5019 A C DIFF
5114 C C SAME
6291 T T SAME
6414 C C SAME
6553 C C SAME
6941 G G SAME


The output (on the data placed at the end of the program after the __DATA__ tag):



Code
1457 3091 4 SAME 
3562 3562 1 DIFF
3778 4124 2 SAME
4229 5019 3 DIFF
5114 6553 4 SAME


As you can see, there is still a small bug, the last line is not processed correctly, but I don't have time right now to fix it. I still post it, since it gives you a good start.

I'll try to come back to it later.


(This post was edited by Laurent_R on Aug 25, 2012, 7:45 AM)


Edit Log:
Post edited by Laurent_R (Veteran) on Aug 25, 2012, 4:07 AM
Post edited by Laurent_R (Veteran) on Aug 25, 2012, 7:42 AM
Post edited by Laurent_R (Veteran) on Aug 25, 2012, 7:45 AM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives