
Chris Charley
User
Oct 11, 2012, 12:52 PM
Post #6 of 6
(1292 views)
|
|
Re: [sessmurda] Improving speed when comparing two lists (nested loop)
[In reply to]
|
Can't Post
|
|
to find a variable to make a hash key that matched between two data sets, and improve speed that way Just using a hash does not 'magically' improve speed. :-) If it is used the way you have set up, it is effectively being accessed linearly to find the matches. I believe you chose the wrong item to be a key, $PAC from the hash %loci. There is no corresponding value in the other file you wish to match against. The correct item to choose as a key is the Scaffold604, Scaffold3712 items. To see if they are present then in the other file, just test the Scaffold... key you have in the other file to see if it is in the hash.
#!/usr/bin/perl use strict; use warnings; my $f1 = <<EOF; Scaffold604 947743 947827 Scaffold604 941827 941924 Scaffold604 938360 938389 Scaffold604 932556 933427 Scaffold3712 176554 176704 Scaffold3712 180811 180934 Scaffold3712 181470 181554 Scaffold446353 19 1400 Scaffold121539 168000 175000 EOF my $f2 = <<EOF; 27051543 Scaffold446353 19 1442 27051545 Scaffold121539 7428 11547 27051546 Scaffold121539 80165 98618 27051547 Scaffold121539 167332 175700 27051549 Scaffold267160 81607 82942 27051550 Scaffold267160 79672 80108 EOF my %data; open my $fh2, '<', \$f2 or die $!; while (<$fh2>) { chomp; my (undef, $scaff, $start, $stop) = split /\t/; push @{ $data{$scaff} }, {start => $start, stop => $stop}; } close $fh2 or die $!; open INSIDE, ">", 'inside.txt' or die $!; open OUTSIDE, ">", 'outside.txt' or die $!; open my $fh1, '<', \$f1 or die $!; while (<$fh1>) { my ($scaff, $field1, $field2) = split /\t/; if (my $aref = $data{$scaff}) { # array reference my (%seen_inside, %seen_outside); for my $href (@$aref) { # hash reference if ($href->{start} - 100 < $field1 && $field2 < $href->{stop} + 100) { print INSIDE unless $seen_inside{$_}++; } else { print OUTSIDE unless $seen_outside{$_}++; } } } } close $fh1 or die $!; close INSIDE or die $!; close OUTSIDE or die $!;
|