1. here I will use the <> operator
Хорошо, вы планируете читать файл построчно.Не забывайте chomp
каждую строку по ходу, иначе вы получите символы новой строки в вашей последовательности.
2. Check to make sure the file only contains acgt or die
if ( <> ne [acgt] ) { die "usage: file must only contain nucleotides \n"; }
В цикле while оператор <>
помещает прочитанную строку в специальную переменную $_
, если вы не назначите ее явно (my $line = <>
).
В приведенном выше коде вы 'читаем одну строку из файла и отбрасываем ее.Вам нужно сохранить эту строку.
Кроме того, оператор ne
сравнивает две строки, а не одну строку и одно регулярное выражение.Здесь вам понадобится оператор !~
(или оператор =~
с отрицательным символьным классом [^acgt]
. Если вам нужен тест без учета регистра, посмотрите на флаг i
для соответствия регулярному выражению.
3. Transcribe the DNA to RNA (Every A replaced by U, T replaced by A, C replaced by G, G replaced by C).
Как сказал GWW, проверьте свою биологию. T-> U - единственный шаг в транскрипции. Вы найдете оператор tr
(транслитерация) полезнымздесь.
4. Take this transcription & break it into 3 character 'codons' starting at the first occurance of "AUG"
not sure but I'm thinking this is where I will start a %hash variables?
Я бы использовал здесь буфер. Определите скаляр вне цикла while(<>)
. Используйте index
чтобы соответствовать «AUG». Если вы не нашли его, поместите последние две базы в этот скаляр (вы можете использовать substr $line, -2, 2
для этого). На следующей итерации цикла добавьте (с .=
) строку кэти две базы и , а затем снова проверяют «AUG». Если вы получите удар, вы будете знать, где, так что вы можете пометить место и начать перевод.5. Take the 3 character "codons" and give them a single letter Symbol (an uppercase one-letter amino acid name)
Assign a key a value using (there are 70 possibilities here so I'm not sure where to store or how to access)
Опять же, как сказал GWW, создайте хеш-таблицу:
%codons = ( AUG => 'M', ...)
.
Затем вы можете использовать (например.) split
построитьмассив текущей строки, которую вы изучаете, строите кодоны по три элемента за раз и извлекайте правильный код аминокислоты из хеш-таблицы.
6.If a gap is encountered a new line is started and process is repeated
not sure but we can assume that gaps are multiples of threes.
Смотри выше.Вы можете проверить наличие пробела с помощью exists $codons{$current_codon}
.
7. Am I approaching this the right way? Is there a Perl function that I'm overlooking that can simplify the main program?
Вы знаете, глядя на вышесказанное, это кажется слишком сложным.Я построил несколько строительных блоков;подпрограммы read_codon
и translate
: я думаю, что они очень помогают логике программы.
Я знаю, что это домашнее задание, но я полагаю, что это может помочь вам почувствовать другие возможные подходы:
use warnings; use strict;
use feature 'state';
# read_codon works by using the new [state][1] feature in Perl 5.10
# both @buffer and $handle represent 'state' on this function:
# Both permits abstracting reading codons from processing the file
# line-by-line.
# Once read_colon is called for the first time, both are initialized.
# Since $handle is a state variable, the current file handle position
# is never reset. Similarly, @buffer always holds whatever was left
# from the previous call.
# The base case is that @buffer contains less than 3bp, in which case
# we need to read a new line, remove the "\n" character,
# split it and push the resulting list to the end of the @buffer.
# If we encounter EOF on the $handle, then we have exhausted the file,
# and the @buffer as well, so we 'return' undef.
# otherwise we pick the first 3bp of the @buffer, join them into a string,
# transcribe it and return it.
sub read_codon {
my ($file) = @_;
state @buffer;
open state $handle, '<', $file or die $!;
if (@buffer < 3) {
my $new_line = scalar <$handle> or return;
chomp $new_line;
push @buffer, split //, $new_line;
}
return transcribe(
join '',
shift @buffer,
shift @buffer,
shift @buffer
);
}
sub transcribe {
my ($codon) = @_;
$codon =~ tr/T/U/;
return $codon;
}
# translate works by using the new [state][1] feature in Perl 5.10
# the $TRANSLATE state is initialized to 0
# as codons are passed to it,
# the sub updates the state according to start and stop codons.
# Since $TRANSLATE is a state variable, it is only initialized once,
# (the first time the sub is called)
# If the current state is 'translating',
# then the sub returns the appropriate amino-acid from the %codes table, if any.
# Thus this provides a logical way to the caller of this sub to determine whether
# it should print an amino-acid or not: if not, the sub will return undef.
# %codes could also be a state variable, but since it is not actually a 'state',
# it is initialized once, in a code block visible form the sub,
# but separate from the rest of the program, since it is 'private' to the sub
{
our %codes = (
AUG => 'M',
...
);
sub translate {
my ($codon) = @_ or return;
state $TRANSLATE = 0;
$TRANSLATE = 1 if $codon =~ m/AUG/i;
$TRANSLATE = 0 if $codon =~ m/U(AA|GA|AG)/i;
return $codes{$codon} if $TRANSLATE;
}
}