biohisham has asked for the wisdom of the Perl Monks concerning the following question:
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);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: char substitution without regexes
by jwkrahn (Abbot) on Sep 30, 2010 at 16:38 UTC | |
|
Re: char substitution without regexes
by ikegami (Patriarch) on Sep 30, 2010 at 17:12 UTC | |
by jwkrahn (Abbot) on Sep 30, 2010 at 17:59 UTC | |
by ikegami (Patriarch) on Sep 30, 2010 at 18:10 UTC | |
by jwkrahn (Abbot) on Sep 30, 2010 at 18:16 UTC | |
by ikegami (Patriarch) on Sep 30, 2010 at 18:28 UTC | |
|
Re: char substitution without regexes
by oko1 (Deacon) on Sep 30, 2010 at 18:41 UTC | |
|
Re: char substitution without regexes
by TomDLux (Vicar) on Sep 30, 2010 at 20:25 UTC | |
|
Re: char substitution without regexes
by Anonymous Monk on Oct 01, 2010 at 12:42 UTC | |
by Soul Singin' (Initiate) on Oct 02, 2010 at 16:12 UTC |