#!/usr/bin/perl
###########
# A short demo of codon counting, typed in with Matt Silverman 
# looking over my shoulder on Jan 25 2006.
# An example of running this is appended at the end of the file.
################
use strict;
use warnings;

# perl documentation : http://perldoc.perl.org/perl.html

my $dna = "actgaacctgactttgtgcaattgcaaaaaaaaaaaaagtagtaatagtattag";
print "dna is '$dna'\n";
print "its length is " . length($dna) . "\n";

my %frequencies;

my $index = 0;
while ( length($dna) >= $index + 3){
  my $three_char = substr $dna, $index, 3;
  print " at index = $index, three_char = $three_char \n";
  $frequencies{$three_char}++;   # Add one to how many times we've seen that.
  $index = $index + 3;
}
print "That's all of 'em.\n\n";

print "Frequencies:\n";
for my $key (sort keys %frequencies){
  print "  freq( $key ) = " . $frequencies{$key} . "\n";
}

__END__

mahoney@cs matt$ ./jan25.pl 
dna is 'actgaacctgactttgtgcaattgcaaaaaaaaaaaaagtagtaatagtattag'
its length is 54
 at index = 0, three_char = act 
 at index = 3, three_char = gaa 
 at index = 6, three_char = cct 
 at index = 9, three_char = gac 
 at index = 12, three_char = ttt 
 at index = 15, three_char = gtg 
 at index = 18, three_char = caa 
 at index = 21, three_char = ttg 
 at index = 24, three_char = caa 
 at index = 27, three_char = aaa 
 at index = 30, three_char = aaa 
 at index = 33, three_char = aaa 
 at index = 36, three_char = aag 
 at index = 39, three_char = tag 
 at index = 42, three_char = taa 
 at index = 45, three_char = tag 
 at index = 48, three_char = tat 
 at index = 51, three_char = tag 
That's all of 'em.

Frequencies:
  freq( aaa ) = 3
  freq( aag ) = 1
  freq( act ) = 1
  freq( caa ) = 2
  freq( cct ) = 1
  freq( gaa ) = 1
  freq( gac ) = 1
  freq( gtg ) = 1
  freq( taa ) = 1
  freq( tag ) = 3
  freq( tat ) = 1
  freq( ttg ) = 1
