On 8 April 2010 11:00, Raymond Wan <r....@aist.go.jp> wrote:
>
> Hi all,
>
> I would like to read in a binary file and extract the 4-byte ints from it.
>  Under Linux, something like "od -t uI".  I got it working as follows:
>
>
> my $buffer = <STDIN>;
> my @buffer = split //, $buffer;
> for (my $i = 0; $i < length ($buffer); $i += 4) {
>  print unpack ('I', $buffer[$i].$buffer[$i + 1].$buffer[$i + 2].$buffer[$i +
> 3]), "\n";
> }
>
>
> And I was wondering if there was a way of doing this without the for loop.
>  (I am referring to the unpack; not the print.)  The perldocs for unpack
> says:
>
> "unpack does the reverse of pack: it takes a string and expands it out into
> a list of values. (In scalar context, it returns merely the first value
> produced.)"
>
> So, I thought this means I could give it a string and get a list of values
> like this:
>
> my @tmp = unpack ('I', $buffer);
>
> which does not work -- it only converts the first 4 bytes into an integer.
>  Anyway, if the above code with a for loop is the best way, I'm happy to
> stick with it -- just wondering if I'm missing out on something with
> unpack...
>
> Thanks!
>
> Ray

Hi Raymond,

Wildcards can be used within the template in pack. There is no need of
the inner loop you have written. For example, to unpack all signed
longs:

my @signed_longs = unpack ( 'I*', $buffer );

Regards,
Alan Haggai Alavi.
-- 
The difference makes the difference

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to