# ACGT String compression and decompression # # We compress to fixed length string, 2 bits per symbol -- zero fill in last byte. my %compress ; # string of up to 4 characters to compressed item my @expand ; # compressed value to string BEGIN { my @ACGT = qw(A C G T) ; my $s = '' ; my $v = 0 ; foreach my $a (@ACGT) { $s = $a ; $compress{$s."\n"} = $compress{$s} = chr($v) ; foreach my $b (@ACGT) { $s = $a.$b ; $compress{$s."\n"} = $compress{$s} = chr($v) ; foreach my $c (@ACGT) { $s = $a.$b.$c ; $compress{$s."\n"} = $compress{$s} = chr($v) ; foreach my $d (@ACGT) { $s = $a.$b.$c.$d ; $compress{$s} = chr($v) ; $expand[$v++] = $s ; } ; } ; } ; } ; $compress{"\n"} = '' ; $compress{''} = '' ; } ; # Compress ACGT string (all upper case) with or without trailing "\n" # # $compressed = acgt_compress(ACGT_STRING) sub acgt_compress { my $c = '' ; $c .= $compress{$_} for unpack('(a4)*', $_[0]) ; return $c ; } ; # Decompress compressed ACGT, and cut to required length # # $acgt_string = acgt_expand(COMPRESSED, LENGTH) sub acgt_expand { my $e = '' ; $e .= $expand[$_] for unpack('C*', $_[0]) ; return substr($e, 0, $_[1]) ; } ;