laziness, impatience, and hubris | |
PerlMonks |
Re: Translation Substring Error (updated)by haukex (Archbishop) |
on Nov 09, 2017 at 15:47 UTC ( [id://1203051]=note: print w/replies, xml ) | Need Help?? |
@seqarray and $seqarray are two different variables, and you never assign anything to $seqarray, so using substr on it does not make much sense, I suspect you just want to look directly at $seq instead of splitting it (BTW, to get multiple elements out of an array, use Slices or splice). Also, note that you overwrite $amino_acid on every loop iteration. The following minimal changes make your code work for me:
<update2> Fixed an off-by-one error in the above code; I initially incorrectly translated your $#seqarray-2 into length($seq)-2 ($#seqarray returns the last index of the array, not its length like scalar(@seqarray) does, or length does for strings). That's a good argument against the classic for(;;) and for the two solutions below instead :-) </update2> If you output the return value from OneFrameTranslation (your current code is ignoring the return value), this gives you:
By the way, you can probably move your %genetic_code to the top of your code (outside of the sub), so that it only gets initialized once instead of on every call to the sub, and making its name uppercase is the usual convention to indicate it is a constant that should not be changed. Another way to break up a string is using regular expressions, the following also works - it matches three characters, and then matches again at the position that the previous match finished, and so on:
Or, possibly going a little overboard, here's a technique I describe in Building Regex Alternations Dynamically to make the replacements using a single regex. I have left out the quotemeta and sort steps only because I know for certain that all keys are three-character strings without any special characters, if you have any doubts about the input data, put those steps back in!
However, note this produces slightly different output for the first input: "MPVC" (the leftover C remains unchanged). Whether or not you want this behavior or not is up to you; it can also be accomplished in the first two solutions (although slightly less elegantly than with a regex). Update: Also, in the first two solutions you haven't defined what would happen if a code happens to not be available in the table; the third regex solution would simply leave it unchanged. Also minor edits for clarification.
In Section
Seekers of Perl Wisdom
|
|