-2

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.

1 Answers1

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
  • 1
    DNA 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
  • 1
    when 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
  • @ysth thanks, I've edited my answer – con Feb 06 '20 at 16:10