[Chicago-talk] Parsing a Hex file

Pete Krawczyk mongers at bsod.net
Fri Jan 19 13:41:30 PST 2007

Subject: Re: [Chicago-talk] Parsing a Hex file
From: Jay Strauss <me at heyjay.com>
Date: Fri, 19 Jan 2007 14:24:49 -0600

}But I can't get the unpack correct (with the proper data types):
}my ($field_num, $value) = unpack("S2, S/A*", $file_contents);

S is a 16-bit integer, according to "perldoc -f pack".  So what you're 
asking for is two shorts, followed by an ASCII string of length determined 
by a third short.  The whitespace is fine, but the comma is ignored - if 
you were using warnings, you'd be told "Invalid type ',' in unpack".

unpack doesn't do the looping you want, as far as I'm aware.  However, I'm 
pretty sure the following loop will do what you're looking for:

    while (length($file_contents)) {
        my ($field_num, $value) = unpack("SC/A", $file_contents);
	# something with $field_num and $value
        my $len = length($value);
        $file_contents = substr($file_contents,$len+3);

Of course, I'm using "C" to mean "8-bit integer", but I don't know any 
more elegant way to do that.

-Pete K
Pete Krawczyk
  mongers at bsod dot net

More information about the Chicago-talk mailing list