in reply to BitStream revisited
It's not clear whether you want failure to read the desired number of bits would be a fatal error or just return what was available.sub BitStream::make_bitstream { my $filename = shift; open my $fh, ... or return my $buf=''; return sub { # if a buffer is available, use it my $ret_str = substr($buf, 0, (defined($_[0]) ? $_[0] : 1), ''); # fill buffer if request may not have been satisfied if (!length($buf)) { my $need = (defined($_[0]) ? $_[0] : 1) - length($ret_Str); return $ret_str if !$need; read from $fh and unpack into $buf $ret_str .= substr($buf, 0, $need, ''); } $ret_str; } } #example package main; $get_bits = BitStream::make_bitstring("foo.dat") or die "open failure: + $!"; $onebit = $get_bits->(); $twobits = $get_bits->(2);
!defined($_[0])||$_[0] may be faster than the ?: way; if you are that concerned, you may want to benchmark it (or just use C :).
Update: - $ret_str was supposed to be - length($ret_str)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: BitStream revisited
by spurperl (Priest) on Jan 01, 2004 at 08:04 UTC |