http://www.perlmonks.org?node_id=857185


in reply to Re: Reading Binary files in Perl
in thread Reading Binary files in Perl

Below is the structure or format of data in binary file: <structure> Offset Field Name size 0x0 magic_numbe 8 0x8 retry_count 1 0x9 number_record 1 0x10 dc_timestamp 8 <\structure> and the code is:
open(FH, "<DCdata.bin") or die "Can't open DCdata.bin file for reading +!"; binmode(FH); while (<FH>) { $index = 0; foreach $field_name (keys (%disk_structure)) { $value = read (FH, $buffer, ($field_name * 8), 0); print tell (FH); print "\n"; } foreach $f_name (keys (%disk_structure_record)) { $value_record = read (FH, $buffer, ($f_name * 8), 0); #print tell (FH)\n; } } close(FILE);

Replies are listed 'Best First'.
Re^3: Reading Binary files in Perl
by BrowserUk (Patriarch) on Aug 25, 2010 at 13:16 UTC

    If your file consists of 18 character records, then the easiest way to read it is to set the input record separator ($/) to a reference to the number of bytes per record: $/ = \18;. This causes readline() (<FH>) to read the file as a series of fixed length records. You can then unpack the fields within each record very easily:

    #! perl -slw use strict; =comment Offset Field Name size 0x0 magic_numbe 8 0x8 retry_count 1 0x9 number_record 1 0x10 dc_timestamp 8 =cut open( FH, '<', DCdata.bin" ) or die "Can't open DCdata.bin file for reading!"; binmode(FH); $/ = \18; ## set record size while( <FH> ) { my( $magic, $retry, $recnum, $timestamp ) = unpack 'A8 C C A8', $_ +; ## Do something with the information?? } close FH;

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re^3: Reading Binary files in Perl
by Corion (Patriarch) on Aug 25, 2010 at 12:59 UTC

    A hash is not ordered, so it makes no sense to read the (ordered) elements from a file in a foreach loop over the hash keys.