Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a String into Equal Length Chunk in Perl

Tags:

split

perl

Let's say I have string of length in multiple of 3.

my $seq = "CTTCGAATT"; # in this case length of 9

Is there a way I can split it into equal length of 3? Such that in the end I have this array:

$VAR = ["CTT", "CGA", "ATT"];
like image 863
neversaint Avatar asked Nov 25 '11 06:11

neversaint


3 Answers

Take a look at the solution at How can I split a string into chunks of two characters each in Perl?

Especially the unpack might be interesting:

my @codons = unpack("(A3)*", $seq);
like image 112
spuelrich Avatar answered Sep 30 '22 13:09

spuelrich


Iterate over multiples of three, using substr to get pieces to push into a list.

like image 33
Alex Reynolds Avatar answered Sep 30 '22 12:09

Alex Reynolds


my $str = join '', map { ('A','T','C','G')[ rand 4 ] } 0 .. 900 ; # Random string

my @codons = $str =~ /[ACTG]{3}/g;   # Process in chunks of three
                                     # '/g' flag necessary

print 'Size of @codons array : ',
        scalar @codons;              # '300'
like image 20
Zaid Avatar answered Sep 30 '22 14:09

Zaid