Your original string contains 9 characters. The form you are compressing to packs 4 characters to a byte, but with no way of knowing how many characters in the last byte are significant.

Update: FWIW you can speed this up considerably by banging 4 characters at a time -- code enclosed, below. However, in my experience a little bit of C will do a lot better -- particularly when reading big chunks of file and getting the C to process many strings at a time.

# ACGT String compression and decompression # # We compress to fixed length string, 2 bits per symbol -- zero fill i +n 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]) ; } ;

In reply to Re: Unpack Fail to Decompress String? by gone2015
in thread Unpack Fail to Decompress String? by neversaint

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.