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

Hello, I'm new to perlmonks and this is my first post! I've only coded in matlab, so I will reference matlab functions to see if you guys can help me find the equivalent in perl.
I"m trying to read binary data from a file. The structure of the file contains data that has information in 158 byte increments, meaning every new 158 bytes is independent from the rest. so it goes like this:
$file = $ARGV_[0]
open(fileFID,$file);
for (my $ii = 1; $ii<=10;$ii++){
read(fileFID,my $data,158);
#now everytime I loop I want to put the new information of
#the file into a new row. In matlab you would simply say:
# $new_data(ii,:)=$data; and the info from read would go
#into a new row. I want to keep the $new_data variable for
#later use because I will be calling it more than once and
#I dont' want to read the information from the file
#everytime. Please help!
}

Replies are listed 'Best First'.
Re: reading binary data from a file
by ikegami (Patriarch) on Oct 28, 2009 at 21:16 UTC
    push
    my $fn = @ARGV[0]; open(my $fh, '<', $fn) or die("Can't open \"$fn\": $!\n"); binmode($fh); my @recs; while (read($fh, my $rec, 158)) { push @recs, $rec; }

    Don't forget binmode on binary files!

      Thank you.

      Now, how do I access the 23rd to 35th byte for every row and put it into another array? In Matlab it would be:
       new_array = array(:,23:35);
      and you're done

      Second, how do I access a row and column in that array and put it into a scalar? In Matlab it would be:
       scalar = array(3,4)
      meaning I'm grabing the 3rd row and 4th column byte.

        substr can be used to extract portions of other strings. It returns a string, though. If you want to treat each character of that string as a byte, you can then use unpack 'C*'.

        Square brackets can be used to create anonymous arrays. The contents of the brackets are assigned to the array. The operator returns a reference to the anonymous array.

        $array[2][3] gets the 4th element of the array referenced by the 2nd element of @array. perllol

        All together:

        my @recs; while (read($fh, my $rec, 158)) { push @recs, [ unpack 'C*', substr($rec, 22, 13) ]; } print $recs[2][3];

        Since you're using unpack anyway, you can just skip over the unwanted bytes instead of using substr.

        push @recs, [ unpack 'x22 C13', $rec ];

        Update: Ooops, was missing the "*" in the unpack format.