in reply to reading binary data from a file

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!

Replies are listed 'Best First'.
Re^2: reading binary data from a file
by amigero (Novice) on Oct 29, 2009 at 00:12 UTC
    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.