I want to write a Perl subroutine using rand() function that generates a random DNA sequence of specified length n. The length n of the sequence is passed as an argument to the subroutine. I would appreciate if someone could help me out as I am a beginner in perl.
Asked
Active
Viewed 365 times
-2
-
1What have you tried so far? – Timur Shtatland Feb 05 '20 at 20:14
-
I cannot come up with any idea – Pasha Talebi Charmchi Feb 05 '20 at 20:23
-
2This isn't a code writing service, but [String::Random](https://metacpan.org/pod/String::Random) can do what you're asking. – Grinnz Feb 05 '20 at 20:26
-
By sequence, do you mean a sequence of bases or a sequence of codons? (Computationally, there's not much difference, but you may want your result to have some specific properties.) – chepner Feb 05 '20 at 20:31
1 Answers
1
FYI normally you put anything that you have tried so far, Stack Overflow isn't a code writing service.
With that in mind, the best way to do this in my humble opinion is with Perl's rand
function:
#!/usr/bin/env perl
use strict; use warnings;
use autodie ':all';
use feature 'say';
my @letters = qw(A C G T);
sub random_DNA {
my $length = shift;
my $seq = '';
foreach my $n (1..$length) {
$seq .= $letters[rand(4)]
}
return $seq
}
foreach my $length (1..9) {
say random_DNA($length)
}
which outputs
con@V:~/Scripts$ perl random_DNA.pl
T
TT
TGG
TGTC
ATGAC
AACGAG
CGGGGTT
CCGTCGTC
TGGCCTCGA
your output will probably not be identical to this, of course, as this is a random function. I prefer not to use modules if I can avoid them, to avoid portability issues, especially with tasks that take a minute to write, like this one.

con
- 5,767
- 8
- 33
- 62
-
1DNA sequence does not work at _random_. There is some physical/chemical law how atoms a binding together. It gets more complicated as one strand must attach to second strand on relation AT, CG to form helix spiral. DNA sequence should be build according this rules otherwise it will not be DNA at all. Mother nature invented two parents to pass this information from parents to children. Week bindings between atoms a subject to mutations and at some rare cases to inherited genetic deceases. – Polar Bear Feb 05 '20 at 21:32
-
Visit following [webpage](https://en.wikipedia.org/wiki/Nucleic_acid_sequence) if above mentioned information sparked an interest in bioinformatics. – Polar Bear Feb 05 '20 at 21:34
-
1when passed a length of 0, this returns undef. It's often good in the `my $s; for ... { ... $s .= ...}` pattern to do `my $s = '';` before the loop. – ysth Feb 05 '20 at 23:42
-