user105033 user105033 - 8 months ago 30
Perl Question

How can I read an unsigned int from a binary file in Perl?

Let's say I have a binary file that is formatted like

[unsigned int(length of text)][text][unsigned int(length of text)][text][unsigned int(length of text)][text]

And that pattern for the file just keeps repeating. How do I read the unsigned int and print it out followed by the text block in Perl?

Again, this is a binary file and not a plain text file.


Here is a small working example.


use strict;
use warnings;

my $INT_SIZE = 2;
my $filename = 'somefile.bin';

open my $fh, '<', $filename or die "Couldn't open file $filename: $!\n";

binmode $fh;

while ( read $fh, my $packed_length, $INT_SIZE ) {

    my $text = '';
    my $length = unpack 'v', $packed_length;

    read $fh, $text, $length;

    print $length, "\t", $text, "\n";

Change INT_SIZE and the size and endianness of the unpack template to suit (either 'v' or 'n' or 'V' or 'N'). See the unpack manpage for more details.