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:
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?.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{$_}; } } }
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);
In reply to char substitution without regexes by biohisham
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |