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

#!/usr/bin/perl Hi ! I have a little question concerning unpack function I have a binary file, from which I read blocks of 71 bytes (in binmode). I want then unpack the data using unpack function but I somehow don't get its functionality...as I understand it It should return an array containing unpacked data according to the given template.. What I do is to read block of data
open INF, $FileName or die "\nCan't open $FileName for reading: $!\n"; binmode INF; while ( ($readBytes = read (INF, $buffer, BLOCK_SIZE )) ){ print 'Read bytes:'.$readBytes."\n"; $BlockCounter++; @data = unpack('C C C C C C C C C C3 C3 C5 C5 C3 C3 C3 C C3 C C12 +C20', $buffer); $tmp = @data; print "Size of DataArray = $tmp\n"; }
What I don't understand is why the size of the array is not equal to the number of templates in template string passed to unpack function but it is still 71 items big as it is the size of the read block(BLOCK_SIZE = 71). I thought unpack works the way as I wrote it, but I was terribly wrong... Can anyone help me with this ? Otherwise I will just have to use substr functions to cut the buffer into such long parts I need ? Thanks!

Replies are listed 'Best First'.
Re: why the unpack doesnt split the data to the array ?
by ikegami (Patriarch) on Aug 06, 2008 at 19:00 UTC
    C5 returns returns 5 numbers, each made from one byte. What would you like to get, a 5 character string? That would be A5.
    >perl -le"$,=', '; print unpack('C5', 'abcdefgh')" 97, 98, 99, 100, 101 >perl -le"$,=', '; print unpack('A5', 'abcdefgh')" abcde
      No no I would like to get an array @data that would contain 21 items (as it is the count of C's in the template ) So that array would look like this: lets say that $buffer contains these data: f07601089978040001aaaaaa2017102195404724203718262a05051219540400 000199000001040678461666aaaaaaaaaaaaaa00023532200000011820050512 19540472403aaa (this is the hexdump of first 71 bytes read from that binary file) And I want these data to be split to the @data array according to the template I use ->> so I want @data to be like this: (f0, 76, 01, 08 AND SO ON ACCORDING TO THE TEMPLATE) - just unpack the particular data as unsigned chars.. But I probably get it wrong :) I'm thinking about that $buffer as a buffer in the C language :(

        What do you think that the C5 does? You use it, and it returns 5 (byte) numbers. It is equivalent to a byte[5] I guess. Maybe you can describe to us what you intend it to do, then we can tell you what other template you should use. Because your "according to the template" is how Perl already behaves. But that does not seem to be what you want.

        so I want @data to be like this: (f0, 76, 01, 08 AND SO ON

        Hex strings?

        just unpack the particular data as unsigned chars

        There is enough data for 71 chars.