Handling Binary data (.gif file example) in Perl
Archive - Originally posted on "The Horse's Mouth" - 2008-01-17 21:36:06 - Graham EllisPerl is very good for handling binary data - it can do things you can't do with other utilities and scripting languages, and things that are very much harder to do in C - that's because C's strings are null terminated and in the case on binary strings, there may be an embedded null anywhere.
Finding good examples is a bit tricky. And that's because binary data tends to come with long and involved specifications. However, a .gif image file has the height and width of the image encoded into the 7th to 10th bytes of the file, so that does make a reasonable example
# Find all files ending in ".gif" in current directory
@files = glob("*.gif");
print ("@files\n");
# Handle each of them in turn
foreach $picture(@files) {
# If we can't open a file, PANIC!
open (FH,$picture) or die ("couldn't open $picture\n");
# Read first 10 bytes into $stuff
read (FH,$stuff,10) ;
# Use "v" as the most significant byte is last - little endian
# Not "n" which is the other way round - big endian
# skip 6 bytes, the pick up 2 x 2-byte integers
# (see the manual for unpack - v means 2 byte integer ;-) )
($wide,$high) = unpack("x6vv",$stuff);
# With a .gif file, these two numbers are the image size!
print "$picture - $wide x $high\n\n";
}
I've put plenty of comments into that code ... good practice ... and so there's not much need for extra detailed description here. But I should add that there's a pack function that's the opposite of unpack if you want to reform binary data, and you can output binary data using the regular print function - nothing special at all is needed.
Yes - it's Perl, yes the code is that short, and when you know the language really well you can write it REALLY quickly!