For starters, you'd get better compressing using one of the numerous compression modules on CPAN. (Some sample queries: Compress, gzip, zip)
The technique used by the code you posted is useful to save space on disk when dealing with lots of small numbers. It takes fewer bytes to save small numbers, and an extra byte to save very large numbers. It's advantage over general purpose compression algorithms is that you can seek to known and unknown positions into the file.
1 byte: 0..127
2 bytes: 128..etc
3 bytes: 16_384
4 bytes: 2_097_152
5 bytes: 268_435_456
6 bytes: 34_359_738_368
7 bytes: 4_398_046_511_104
8 bytes: 562_949_953_421_312
9 bytes: 72_057_594_037_927_936
Depending on the size of the ints on your system and the precision of floats on your system, some of the above aren't available or more than the above is available.
Untested:
sub compress_uint {
my ($uint) = @_;
my $compressed = '';
while ($uint >= 128) {
$compressed .= chr(($uint & 127) | 128);
$uint >>= 7;
}
$compressed .= chr($uint);
}
for (100, 1000, 100000) {
print $fh compress_uint($_);
}
sub decompress_uint {
our $compressed; local *compressed = \($_[0]);
my $bytes_read = 0;
my $uint = 0;
for (;;) {
die if length($compressed) == $bytes_read;
my $byte = ord(substr($compressed, $bytes_read++, 1));
$uint = ($uint << 7) | ($byte & 127);
last if $byte & 128;
}
$compressed = substr($compressed, $bytes_read);
}
my $raw = do { local $/; <$fh> };
my @nums;
while (length($raw)) {
push @nums, decompress_uint($raw);
}
Update: Fixed some typos in text and code.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.