Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Problem computing GC content

by Kenosis (Priest)
on Jul 14, 2014 at 17:03 UTC ( [id://1093586]=note: print w/replies, xml ) Need Help??


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!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1093586]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (2)
As of 2024-04-19 22:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found