Archive - Originally posted on "The Horse's Mouth" - 2010-06-10 20:23:21 - Graham Ellis
During today's Perl course, I was asked to provide an example of the unpack function for extracting multiple values from a piece of data - typically binary data extracted from a file into a scalar variable.
Dorothy-2:de$ perl imgsize sd*.gif
sd1.gif is GIF, 89a, 450 by 250
sd2.gif is GIF, 89a, 250 by 300
sd3.gif is GIF, 89a, 300 by 250
sd4.gif is GIF, 89a, 333 by 333
Dorothy-2:de$
And what better images to illustrate the article that ones of the delegates on the course?
Here's the program:
for $file(@ARGV) {
open (FH,$file);
read (FH,$header,10);
($type,$st,$wid,$hei) = unpack("a3a3vv",$header);
print ("$file is $type, $st, $wid by $hei\n");
}
From memory (!) I recalled that a .gif file starts with 3 bytes to confirm that it's a GIF file, 3 bytes to tell us which subformat has been used, and 2 2-byte 16 bit unsigned integers, bigendian, which tell the width and height of the image in pixels.
You'll notice that the course had a lot of delegate on it. Where there's a high number of delegates, all at a similar level, all from the same company, and all doing similar applications, I will let the customer place up to 20 delegates on a course. Where the delegates background differs, I request a reduced top number. And on a public course, where people from differnt companies book, we restrict delegates to just 8 so that there's a good opportunity for the tutor to talk to each and every delegate about their own individual use of the subject being taught.
P.S. There's another example of unpack on a .gif file - [here] - that I wrote a wile back; the techniques used are slightly different, and the program is one that came from a series named after British Rivers - in this case the Ystwyth from Aberystwyth fame.