Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Keeping track of substituted regions with a while loop

by choroba (Abbot)
on Nov 15, 2013 at 22:59 UTC ( #1062816=note: print w/ replies, xml ) Need Help??


in reply to [SOLVED] Keeping track of substituted regions with a while loop

You interpretation is correct. Use /g and Perl will keep track of the position in the string itself:

$rna =~ s/(...)/$gencode{$1}/g;
لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ


Comment on Re: Keeping track of substituted regions with a while loop
Select or Download Code
Re^2: Keeping track of substituted regions with a while loop
by enderk (Novice) on Nov 16, 2013 at 13:28 UTC

    Wow, choroba, thanks for that! That gives me exactly what I wanted to do using a substitution regex expression. This means I don't need to use a while loop in my code as the g modifier will ensure the regex expression "walks" along the string.

    For future reference, in case anyone stumbles across this node, I'll paste the modified code below. Hopefully someone else will learn as much about regular expressions as I did today :)

    use strict; use warnings; open READER, '<', 'rna.txt'; chomp(my $rna = <READER>); close READER; my %gencode; open GENCODE, '<', 'code.txt'; while (<GENCODE> =~ m/^([AUGC]{3}) (\w)?$/m) { my $codon = $1; my $aa; if (defined $2) { $aa = $2; } else { # $aa = 'STOP'; $aa = ''; } $gencode{$codon} = $aa; } close GENCODE; my $protein = $rna; $protein =~ s/([AUGC]{3})/$gencode{$1}/g; open RESULTS, '>', 'results.txt'; print RESULTS "$protein\n"; close RESULTS;

    Also for the record, I know that now, I don't necessarily have to duplicate the $rna string into the $protein string, but I have left that in nevertheless as I think it makes the code conceptually easier to understand.

    Thanks a lot to both of you for trying to help me out

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1062816]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (7)
As of 2014-07-30 04:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (229 votes), past polls