Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks, I have some binary data files from which I need to read data. Each of the records in the file are 4800 bytes, and so I wrote this code:
my ($filename) = shift @_; my ($ref_data) = shift @_; my ($buff, $num_records); open DATA, "<", $filename or die "Cannot open file $filename - + $!\n"; binmode(DATA); while (read(DATA, $buff, 4800)) { #print "$buff\n"; # update ref_data, recording values of data, etc } print "Processed $num_records records in file $filename\n"; close (DATA);
Within each of those 4800 bytes, there's a header (300 bytes), followed by 250 subrecords of 18 bytes each. I need to see the byte values of each of the subrecords. I thought the code would entail something like chopping off the header, recording that, and doing the same with each of the subrecords, which would in turn, get chopped up and recorded. However, I can't seem to figure out a straightforward way to do this. All the stuff I've found is for reading bytes off a filehandle, not from a string, and I know substr is pretty inefficient. Would using regexps be appropriate here? Anybody have thoughts on how to implement this?

Replies are listed 'Best First'.
Re: Reading nested records in binary data
by BrowserUk (Patriarch) on Mar 10, 2006 at 00:59 UTC

    It really depends upon what you mean by efficiency?

    If notational convenience is your goal, then unpack wins hands down; but if execution efficiency is required, you might reconsider the use of substr. Some results from a benchmark:

    C:\test>535539 Test data: 1000 records Rate unpack substr lrefs unpack 1.77/s -- -33% -99% substr 2.65/s 50% -- -99% lrefs 196/s 10974% 7289% --

    As you can see, the time taken to re-parse the template each time around the loop, means that substr is 50% quicker that unpack.

    Even with substr, you are still having to re-divide the buffer and extract the substrings to an array. The method labelled 'lrefs' avoids doing this with the result that it runs two orders of magnitude more quickly.

    It does this by pre-allocating a buffer to the record size and then making an array of references into that buffer. It then reads each new record into the pre-subdivided buffer and uses the references to extract the subrecords:

    my $buffer = chr(0) x 4800; ## Pre-partition the data using lvalue refs my $header = \substr $buffer, 0, 300; my @subs = map{ \substr( $buffer, 300 + $_ *18, 18 ) } 0 .. 249; while( read( $fhTest, $buffer, 4800, 0 ) == 4800 ) { ... }

    The removal of this 'invariant code' from the loop, combined with avoiding the need to deallocated/reallocate the array elements for the subrecords each time around are what makes this so efficient.

    Of course, if you need to store the data for later use outside the loop (by building a hash say), then you'll need to allcate the space to store it and some of the efficiency gains will be lost:

    C:\test>535539 Test data: 1000 records Rate unpack substr lrefs unpack 1.48/s -- -17% -40% substr 1.78/s 20% -- -28% lrefs 2.46/s 66% 38% --

    Even so, 40% gain over substr and 66% over unpack is worth having if you are processing a large amount of data, even with the (slight) decrease in notational convenience.

    The benchmark code:

    Uncomment the hash assignments to see the reduced performance if you need the data outside the loop, and the print statements to convince yourself that they all do the same thing.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Reading nested records in binary data
by Corion (Patriarch) on Mar 09, 2006 at 22:39 UTC

    How do you know that substr is pretty inefficient?

    Anyway, I'd use unpack for this, as it deals pretty well with extracting fixed-length stuff from strings:

    my ($header, @items) = unpack "a300(a18)250", $buff;
      I think I answered my own question. I think it should be -
      my ($header, @items) = unpack "a300" . "a18" x 250, $buff;
      Well, I tried that code for unpack, and I get an error -
       Invalid type in unpack: '(' at code.pl line 98
      . Is that the correct syntax for the template?

        Older versions of perl don't understand ( in pack/unpack templates. I believe that template syntax was introduced in perl 5.8.

      Thanks, I'll try unpack. Re: substr, since these are fixed length records, it takes less effort to use unpack, like you have in your code, as opposed to using substr multiple times. This is, of course, based on intuition - I know how efficient code actually is depends on other factors too. But I like less code :)
Re: Reading nested records in binary data
by GrandFather (Saint) on Mar 09, 2006 at 22:48 UTC