http://www.perlmonks.org?node_id=1093586


in reply to Problem computing GC content

Here's another option:

use strict; use warnings; local $/ = '>'; while (<>) { chomp; /\S/ or next; my ( $id, $seq ) = /(.+?)\n(.+)/s; $seq =~ s/\n//g; my $GCcount = $seq =~ tr/GC//; printf "%s, %.2f%%\n", ">$id", ( $GCcount / length $seq ) * 100; }

Command-line usage: perl script.pl fastaFile [>outfile]

The last, optional parameter directs output to a file.

Sample FASTA record:

>gi|5524211|gb|AAD44166.1| cytochrome b [Elephas maximus maximus] LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG LLILILLLLLLALLSPDMLGDPDNHMPADPLNTPLHIKPEWYFLFAYAILRSVPNKLGGVLALFLSIVIL GLMPFLHTSKHRSMMLRPLSQALFWTLTMDLLTLTWIGSQPVEYPYTIIGQMASILYFSIILAFLPIAGX IENY

Output on that sample FASTA record:

>gi|5524211|gb|AAD44166.1| cytochrome b [Elephas maximus maximus], 7.3 +9%

Since FASTA files use ">" as the record separator, the script sets Perl's record separator to that character, so the file's read one FASTA record at a time. After a read, chomp removes that record separator.

Next, /\s/ tests to see that there are characters to parse and, if not, the next record is read. Using a regex, the id and seq are captured. A substitution is used to remove any newlines, so an accurate length count can be made. (The sequence in FASTA records may be across multiple lines; this script will handle these.)

As AnomalousMonk demonstrated, Perl's transliteration operator can be used to get the GC character count within the sequence. Finally, the results are printed using printf.

Hope this helps!