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

As a TOTAL perl novice, I want to know how to read a binary file conisting of 32 bit integers and do something useful with the data (like store the values in an array). OK... Tell me to go read a book and stop wasting your time if you like.

Replies are listed 'Best First'.
Re: Reading Binary
by Abigail-II (Bishop) on Jun 06, 2002 at 12:01 UTC
    Open the file (possibly in binmode if you have a silly platform), read in chunks of data (make sure you are reading in chucks that are a multiple of 4 bytes) - either with sysread, or just <> (for the latter, set $/ to a reference to the amount of bytes you want to read), and use unpack to translate the raw bytes to integers.

    Here's an example:

    #!/usr/bin/perl use strict; use warnings 'all'; open my $fh => "< /tmp/foo" or die $!; $/ = \100; while (<$fh>) { my @nums = unpack "L*" => $_; print "@nums\n"; } close $fh; __END__

    Note that I used L in the unpack routine. This is garanteed to be exactly 32 bits, unlike I which is at least 32 bits.

    Abigail

Re: Reading Binary
by broquaint (Abbot) on Jun 06, 2002 at 12:03 UTC
    I'd advice reading up on the duel binary ninja-like functions of pack() and unpack() for all your bit munging needs. Not being as familiar as I'd like with these ubiquitous bit twiddling functions I shall only give a small example of code
    open(my $fh, "binary.file") or die("ack - $!"); my $chunk; while(read($fh, $chunk, 4)) { my $data = unpack("i", $chunk); print "data is $data\n"; }
    This works fine on a file containing a bunch of integers on my linux system, so it may need tweaking from platform to platform (see. Abigail-II's note about using L pack format).
    HTH

    _________
    broquaint

Re: Reading Binary
by Joost (Canon) on Jun 06, 2002 at 11:50 UTC
    I'll tell you to read this :-)
    perldoc perl perldoc -f open perldoc -f read perldoc -f binmode perldoc -f pack perldoc -f unpack
    As for books, you might try 'Learning Perl' or dive in at the deeper end and get 'Programming Perl' (the 3rd edition is a little easier for novices than the first 2). Both books are published by O'Reilly.
    -- Joost downtime n. The period during which a system is error-free and immune from user input.
Re: Reading Binary
by marvell (Pilgrim) on Jun 06, 2002 at 11:53 UTC
Re: Reading Binary
by Anonymous Monk on Jun 06, 2002 at 14:55 UTC
    Wow! Thanks for the tips guys. And I expected to get my head bitten off!
Re: Reading Binary
by marvell (Pilgrim) on Jun 06, 2002 at 11:53 UTC