A colleague of mine is learning Perl, he approached me with an interesting problem that got him running in circles !. He basically has this string of DNA letters (
qw(a g c t)) that he wants to get its
reverse complement - reading the string backwards and replacing every letter to the one complementary to it (i.e a<->t, g<->c).
The book exercise requires him to achieve this task by specifically using substr and without using any regex at all, after him trying his best I gave him the following code:
use strict;
use warnings;
my $string = "aaaggctt";
my %hash = qw(a t g c c g t a);
print "The DNA string is: \n";
print $string,"\n";
print "The reverse complement is: \n";
#One way to do it... 1st chunk..
for (my $i = length($string); $i>= 0 ; $i--){
for (keys %hash){
print substr($string, $i, 1) eq $_ ? $hash{$_} : '';
}
}
print "\n"
#Expansion of the previous solution.. 2nd chunk..
for (my $i = length($string); $i>= 0 ; $i--){
for (keys %hash){
if(substr($string, $i, 1) eq $_ ){
print $hash{$_};
}
}
}
I am interested in two issues. Firstly, will ye wise monks rear forward a TIMTOWDI solution that doesn't use a substitution regex? and that doesn't necessarily use
substr, so we can learn something new?.
Secondly, benchmarking the two fragments showed me variations in the code speed that sometimes the first code chunk executes faster and other times slower than the second code chunk !. Briefly, I am using the module Benchmark as follows :
$t1 = Benchmark->new;
# First chunk from the code above
$t2 = Benchmark->new;
$t3 = Benchmark->new;
# Second chunk from the code above
$t4 = Benchmark->new;
$td1 = timediff($t2-$t1);
$td2 = timediff($t4-$t3);
print timestr($td1),"\n",timestr($td2);
Excellence is an Endeavor of Persistence.
A Year-Old Monk :D .