Update Changes.
[p5sagit/p5-mst-13.2.git] / pod / perlpacktut.pod
CommitLineData
34babc16 1=head1 NAME
2
3perlpacktut - tutorial on C<pack> and C<unpack>
4
5=head1 DESCRIPTION
6
7C<pack> and C<unpack> are two functions for transforming data according
8to a user-defined template, between the guarded way Perl stores values
47b6252e 9and some well-defined representation as might be required in the
34babc16 10environment of a Perl program. Unfortunately, they're also two of
11the most misunderstood and most often overlooked functions that Perl
12provides. This tutorial will demystify them for you.
13
14
15=head1 The Basic Principle
16
17Most programming languages don't shelter the memory where variables are
18stored. In C, for instance, you can take the address of some variable,
19and the C<sizeof> operator tells you how many bytes are allocated to
20the variable. Using the address and the size, you may access the storage
21to your heart's content.
22
23In Perl, you just can't access memory at random, but the structural and
24representational conversion provided by C<pack> and C<unpack> is an
25excellent alternative. The C<pack> function converts values to a byte
26sequence containing representations according to a given specification,
27the so-called "template" argument. C<unpack> is the reverse process,
28deriving some values from the contents of a string of bytes. (Be cautioned,
29however, that not all that has been packed together can be neatly unpacked -
30a very common experience as seasoned travellers are likely to confirm.)
31
32Why, you may ask, would you need a chunk of memory containing some values
33in binary representation? One good reason is input and output accessing
34some file, a device, or a network connection, whereby this binary
35representation is either forced on you or will give you some benefit
36in processing. Another cause is passing data to some system call that
37is not available as a Perl function: C<syscall> requires you to provide
38parameters stored in the way it happens in a C program. Even text processing
39(as shown in the next section) may be simplified with judicious usage
40of these two functions.
41
42To see how (un)packing works, we'll start with a simple template
43code where the conversion is in low gear: between the contents of a byte
44sequence and a string of hexadecimal digits. Let's use C<unpack>, since
47b6252e 45this is likely to remind you of a dump program, or some desperate last
34babc16 46message unfortunate programs are wont to throw at you before they expire
47into the wild blue yonder. Assuming that the variable C<$mem> holds a
48sequence of bytes that we'd like to inspect without assuming anything
49about its meaning, we can write
50
51 my( $hex ) = unpack( 'H*', $mem );
52 print "$hex\n";
53
54whereupon we might see something like this, with each pair of hex digits
55corresponding to a byte:
56
57 41204d414e204120504c414e20412043414e414c2050414e414d41
58
47b6252e 59What was in this chunk of memory? Numbers, characters, or a mixture of
34babc16 60both? Assuming that we're on a computer where ASCII (or some similar)
61encoding is used: hexadecimal values in the range C<0x40> - C<0x5A>
47f22e19 62indicate an uppercase letter, and C<0x20> encodes a space. So we might
34babc16 63assume it is a piece of text, which some are able to read like a tabloid;
64but others will have to get hold of an ASCII table and relive that
65firstgrader feeling. Not caring too much about which way to read this,
66we note that C<unpack> with the template code C<H> converts the contents
67of a sequence of bytes into the customary hexadecimal notation. Since
68"a sequence of" is a pretty vague indication of quantity, C<H> has been
69defined to convert just a single hexadecimal digit unless it is followed
70by a repeat count. An asterisk for the repeat count means to use whatever
71remains.
72
73The inverse operation - packing byte contents from a string of hexadecimal
74digits - is just as easily written. For instance:
75
76 my $s = pack( 'H2' x 10, map { "3$_" } ( 0..9 ) );
77 print "$s\n";
78
79Since we feed a list of ten 2-digit hexadecimal strings to C<pack>, the
80pack template should contain ten pack codes. If this is run on a computer
81with ASCII character coding, it will print C<0123456789>.
82
83
84=head1 Packing Text
85
86Let's suppose you've got to read in a data file like this:
87
88 Date |Description | Income|Expenditure
89 01/24/2001 Ahmed's Camel Emporium 1147.99
90 01/28/2001 Flea spray 24.99
91 01/29/2001 Camel rides to tourists 235.00
92
93How do we do it? You might think first to use C<split>; however, since
94C<split> collapses blank fields, you'll never know whether a record was
95income or expenditure. Oops. Well, you could always use C<substr>:
96
97 while (<>) {
98 my $date = substr($_, 0, 11);
99 my $desc = substr($_, 12, 27);
100 my $income = substr($_, 40, 7);
101 my $expend = substr($_, 52, 7);
102 ...
103 }
104
105It's not really a barrel of laughs, is it? In fact, it's worse than it
106may seem; the eagle-eyed may notice that the first field should only be
10710 characters wide, and the error has propagated right through the other
108numbers - which we've had to count by hand. So it's error-prone as well
109as horribly unfriendly.
110
111Or maybe we could use regular expressions:
7207e29d 112
34babc16 113 while (<>) {
114 my($date, $desc, $income, $expend) =
115 m|(\d\d/\d\d/\d{4}) (.{27}) (.{7})(.*)|;
116 ...
117 }
118
119Urgh. Well, it's a bit better, but - well, would you want to maintain
120that?
121
122Hey, isn't Perl supposed to make this sort of thing easy? Well, it does,
123if you use the right tools. C<pack> and C<unpack> are designed to help
124you out when dealing with fixed-width data like the above. Let's have a
125look at a solution with C<unpack>:
126
127 while (<>) {
128 my($date, $desc, $income, $expend) = unpack("A10xA27xA7A*", $_);
129 ...
130 }
131
132That looks a bit nicer; but we've got to take apart that weird template.
133Where did I pull that out of?
134
135OK, let's have a look at some of our data again; in fact, we'll include
136the headers, and a handy ruler so we can keep track of where we are.
137
138 1 2 3 4 5
139 1234567890123456789012345678901234567890123456789012345678
140 Date |Description | Income|Expenditure
141 01/28/2001 Flea spray 24.99
142 01/29/2001 Camel rides to tourists 235.00
143
47b6252e 144From this, we can see that the date column stretches from column 1 to
34babc16 145column 10 - ten characters wide. The C<pack>-ese for "character" is
146C<A>, and ten of them are C<A10>. So if we just wanted to extract the
147dates, we could say this:
148
149 my($date) = unpack("A10", $_);
150
151OK, what's next? Between the date and the description is a blank column;
152we want to skip over that. The C<x> template means "skip forward", so we
153want one of those. Next, we have another batch of characters, from 12 to
15438. That's 27 more characters, hence C<A27>. (Don't make the fencepost
155error - there are 27 characters between 12 and 38, not 26. Count 'em!)
156
157Now we skip another character and pick up the next 7 characters:
158
159 my($date,$description,$income) = unpack("A10xA27xA7", $_);
160
161Now comes the clever bit. Lines in our ledger which are just income and
162not expenditure might end at column 46. Hence, we don't want to tell our
163C<unpack> pattern that we B<need> to find another 12 characters; we'll
164just say "if there's anything left, take it". As you might guess from
165regular expressions, that's what the C<*> means: "use everything
166remaining".
167
168=over 3
169
170=item *
171
172Be warned, though, that unlike regular expressions, if the C<unpack>
173template doesn't match the incoming data, Perl will scream and die.
174
175=back
176
177
178Hence, putting it all together:
179
180 my($date,$description,$income,$expend) = unpack("A10xA27xA7A*", $_);
181
182Now, that's our data parsed. I suppose what we might want to do now is
183total up our income and expenditure, and add another line to the end of
184our ledger - in the same format - saying how much we've brought in and
185how much we've spent:
186
187 while (<>) {
188 my($date, $desc, $income, $expend) = unpack("A10xA27xA7xA*", $_);
189 $tot_income += $income;
190 $tot_expend += $expend;
191 }
192
193 $tot_income = sprintf("%.2f", $tot_income); # Get them into
194 $tot_expend = sprintf("%.2f", $tot_expend); # "financial" format
195
196 $date = POSIX::strftime("%m/%d/%Y", localtime);
197
198 # OK, let's go:
199
200 print pack("A10xA27xA7xA*", $date, "Totals", $tot_income, $tot_expend);
201
202Oh, hmm. That didn't quite work. Let's see what happened:
203
204 01/24/2001 Ahmed's Camel Emporium 1147.99
205 01/28/2001 Flea spray 24.99
206 01/29/2001 Camel rides to tourists 1235.00
207 03/23/2001Totals 1235.001172.98
208
209OK, it's a start, but what happened to the spaces? We put C<x>, didn't
210we? Shouldn't it skip forward? Let's look at what L<perlfunc/pack> says:
211
212 x A null byte.
213
214Urgh. No wonder. There's a big difference between "a null byte",
215character zero, and "a space", character 32. Perl's put something
216between the date and the description - but unfortunately, we can't see
217it!
218
219What we actually need to do is expand the width of the fields. The C<A>
220format pads any non-existent characters with spaces, so we can use the
221additional spaces to line up our fields, like this:
222
223 print pack("A11 A28 A8 A*", $date, "Totals", $tot_income, $tot_expend);
224
225(Note that you can put spaces in the template to make it more readable,
226but they don't translate to spaces in the output.) Here's what we got
227this time:
228
229 01/24/2001 Ahmed's Camel Emporium 1147.99
230 01/28/2001 Flea spray 24.99
231 01/29/2001 Camel rides to tourists 1235.00
232 03/23/2001 Totals 1235.00 1172.98
233
234That's a bit better, but we still have that last column which needs to
235be moved further over. There's an easy way to fix this up:
236unfortunately, we can't get C<pack> to right-justify our fields, but we
237can get C<sprintf> to do it:
238
239 $tot_income = sprintf("%.2f", $tot_income);
240 $tot_expend = sprintf("%12.2f", $tot_expend);
241 $date = POSIX::strftime("%m/%d/%Y", localtime);
242 print pack("A11 A28 A8 A*", $date, "Totals", $tot_income, $tot_expend);
243
244This time we get the right answer:
245
246 01/28/2001 Flea spray 24.99
247 01/29/2001 Camel rides to tourists 1235.00
248 03/23/2001 Totals 1235.00 1172.98
249
250So that's how we consume and produce fixed-width data. Let's recap what
251we've seen of C<pack> and C<unpack> so far:
252
253=over 3
254
255=item *
256
257Use C<pack> to go from several pieces of data to one fixed-width
258version; use C<unpack> to turn a fixed-width-format string into several
259pieces of data.
260
261=item *
262
263The pack format C<A> means "any character"; if you're C<pack>ing and
264you've run out of things to pack, C<pack> will fill the rest up with
265spaces.
266
267=item *
268
269C<x> means "skip a byte" when C<unpack>ing; when C<pack>ing, it means
270"introduce a null byte" - that's probably not what you mean if you're
271dealing with plain text.
272
273=item *
274
275You can follow the formats with numbers to say how many characters
276should be affected by that format: C<A12> means "take 12 characters";
277C<x6> means "skip 6 bytes" or "character 0, 6 times".
278
279=item *
280
281Instead of a number, you can use C<*> to mean "consume everything else
282left".
283
284B<Warning>: when packing multiple pieces of data, C<*> only means
285"consume all of the current piece of data". That's to say
286
287 pack("A*A*", $one, $two)
288
289packs all of C<$one> into the first C<A*> and then all of C<$two> into
290the second. This is a general principle: each format character
291corresponds to one piece of data to be C<pack>ed.
292
293=back
294
295
296
297=head1 Packing Numbers
298
299So much for textual data. Let's get onto the meaty stuff that C<pack>
300and C<unpack> are best at: handling binary formats for numbers. There is,
301of course, not just one binary format - life would be too simple - but
302Perl will do all the finicky labor for you.
303
304
305=head2 Integers
306
307Packing and unpacking numbers implies conversion to and from some
308I<specific> binary representation. Leaving floating point numbers
309aside for the moment, the salient properties of any such representation
310are:
311
312=over 4
313
314=item *
315
316the number of bytes used for storing the integer,
317
318=item *
319
320whether the contents are interpreted as a signed or unsigned number,
321
322=item *
323
324the byte ordering: whether the first byte is the least or most
325significant byte (or: little-endian or big-endian, respectively).
326
327=back
328
329So, for instance, to pack 20302 to a signed 16 bit integer in your
330computer's representation you write
331
332 my $ps = pack( 's', 20302 );
333
334Again, the result is a string, now containing 2 bytes. If you print
335this string (which is, generally, not recommended) you might see
336C<ON> or C<NO> (depending on your system's byte ordering) - or something
337entirely different if your computer doesn't use ASCII character encoding.
338Unpacking C<$ps> with the same template returns the original integer value:
339
340 my( $s ) = unpack( 's', $ps );
341
342This is true for all numeric template codes. But don't expect miracles:
47b6252e 343if the packed value exceeds the allotted byte capacity, high order bits
34babc16 344are silently discarded, and unpack certainly won't be able to pull them
345back out of some magic hat. And, when you pack using a signed template
346code such as C<s>, an excess value may result in the sign bit
347getting set, and unpacking this will smartly return a negative value.
348
34916 bits won't get you too far with integers, but there is C<l> and C<L>
350for signed and unsigned 32-bit integers. And if this is not enough and
351your system supports 64 bit integers you can push the limits much closer
352to infinity with pack codes C<q> and C<Q>. A notable exception is provided
353by pack codes C<i> and C<I> for signed and unsigned integers of the
354"local custom" variety: Such an integer will take up as many bytes as
355a local C compiler returns for C<sizeof(int)>, but it'll use I<at least>
35632 bits.
357
358Each of the integer pack codes C<sSlLqQ> results in a fixed number of bytes,
359no matter where you execute your program. This may be useful for some
360applications, but it does not provide for a portable way to pass data
361structures between Perl and C programs (bound to happen when you call
362XS extensions or the Perl function C<syscall>), or when you read or
363write binary files. What you'll need in this case are template codes that
364depend on what your local C compiler compiles when you code C<short> or
365C<unsigned long>, for instance. These codes and their corresponding
366byte lengths are shown in the table below. Since the C standard leaves
367much leeway with respect to the relative sizes of these data types, actual
368values may vary, and that's why the values are given as expressions in
369C and Perl. (If you'd like to use values from C<%Config> in your program
370you have to import it with C<use Config>.)
371
372 signed unsigned byte length in C byte length in Perl
f8b4d74f 373 s! S! sizeof(short) $Config{shortsize}
374 i! I! sizeof(int) $Config{intsize}
375 l! L! sizeof(long) $Config{longsize}
376 q! Q! sizeof(longlong) $Config{longlongsize}
34babc16 377
378The C<i!> and C<I!> codes aren't different from C<i> and C<I>; they are
379tolerated for completeness' sake.
380
381
382=head2 Unpacking a Stack Frame
383
384Requesting a particular byte ordering may be necessary when you work with
47f22e19 385binary data coming from some specific architecture whereas your program could
34babc16 386run on a totally different system. As an example, assume you have 24 bytes
387containing a stack frame as it happens on an Intel 8086:
388
389 +---------+ +----+----+ +---------+
390 TOS: | IP | TOS+4:| FL | FH | FLAGS TOS+14:| SI |
391 +---------+ +----+----+ +---------+
392 | CS | | AL | AH | AX | DI |
393 +---------+ +----+----+ +---------+
394 | BL | BH | BX | BP |
395 +----+----+ +---------+
396 | CL | CH | CX | DS |
397 +----+----+ +---------+
398 | DL | DH | DX | ES |
399 +----+----+ +---------+
400
401First, we note that this time-honored 16-bit CPU uses little-endian order,
402and that's why the low order byte is stored at the lower address. To
403unpack such a (signed) short we'll have to use code C<v>. A repeat
404count unpacks all 12 shorts:
405
406 my( $ip, $cs, $flags, $ax, $bx, $cd, $dx, $si, $di, $bp, $ds, $es ) =
407 unpack( 'v12', $frame );
408
409Alternatively, we could have used C<C> to unpack the individually
410accessible byte registers FL, FH, AL, AH, etc.:
411
412 my( $fl, $fh, $al, $ah, $bl, $bh, $cl, $ch, $dl, $dh ) =
413 unpack( 'C10', substr( $frame, 4, 10 ) );
414
415It would be nice if we could do this in one fell swoop: unpack a short,
416back up a little, and then unpack 2 bytes. Since Perl I<is> nice, it
417proffers the template code C<X> to back up one byte. Putting this all
418together, we may now write:
419
420 my( $ip, $cs,
421 $flags,$fl,$fh,
422 $ax,$al,$ah, $bx,$bl,$bh, $cx,$cl,$ch, $dx,$dl,$dh,
423 $si, $di, $bp, $ds, $es ) =
424 unpack( 'v2' . ('vXXCC' x 5) . 'v5', $frame );
425
47f22e19 426We've taken some pains to construct the template so that it matches
34babc16 427the contents of our frame buffer. Otherwise we'd either get undefined values,
428or C<unpack> could not unpack all. If C<pack> runs out of items, it will
47f22e19 429supply null strings (which are coerced into zeroes whenever the pack code
430says so).
34babc16 431
432
433=head2 How to Eat an Egg on a Net
434
435The pack code for big-endian (high order byte at the lowest address) is
436C<n> for 16 bit and C<N> for 32 bit integers. You use these codes
437if you know that your data comes from a compliant architecture, but,
438surprisingly enough, you should also use these pack codes if you
439exchange binary data, across the network, with some system that you
440know next to nothing about. The simple reason is that this
441order has been chosen as the I<network order>, and all standard-fearing
442programs ought to follow this convention. (This is, of course, a stern
443backing for one of the Lilliputian parties and may well influence the
444political development there.) So, if the protocol expects you to send
445a message by sending the length first, followed by just so many bytes,
446you could write:
447
448 my $buf = pack( 'N', length( $msg ) ) . $msg;
449
450or even:
451
452 my $buf = pack( 'NA*', length( $msg ), $msg );
453
454and pass C<$buf> to your send routine. Some protocols demand that the
455count should include the length of the count itself: then just add 4
456to the data length. (But make sure to read L<"Lengths and Widths"> before
457you really code this!)
458
459
460
461=head2 Floating point Numbers
462
463For packing floating point numbers you have the choice between the
464pack codes C<f> and C<d> which pack into (or unpack from) single-precision or
465double-precision representation as it is provided by your system. (There
466is no such thing as a network representation for reals, so if you want
467to send your real numbers across computer boundaries, you'd better stick
468to ASCII representation, unless you're absolutely sure what's on the other
469end of the line.)
470
471
472
473=head1 Exotic Templates
474
475
476=head2 Bit Strings
477
478Bits are the atoms in the memory world. Access to individual bits may
479have to be used either as a last resort or because it is the most
480convenient way to handle your data. Bit string (un)packing converts
481between strings containing a series of C<0> and C<1> characters and
482a sequence of bytes each containing a group of 8 bits. This is almost
483as simple as it sounds, except that there are two ways the contents of
484a byte may be written as a bit string. Let's have a look at an annotated
485byte:
486
487 7 6 5 4 3 2 1 0
488 +-----------------+
489 | 1 0 0 0 1 1 0 0 |
490 +-----------------+
491 MSB LSB
492
493It's egg-eating all over again: Some think that as a bit string this should
494be written "10001100" i.e. beginning with the most significant bit, others
495insist on "00110001". Well, Perl isn't biased, so that's why we have two bit
496string codes:
497
498 $byte = pack( 'B8', '10001100' ); # start with MSB
499 $byte = pack( 'b8', '00110001' ); # start with LSB
500
501It is not possible to pack or unpack bit fields - just integral bytes.
502C<pack> always starts at the next byte boundary and "rounds up" to the
503next multiple of 8 by adding zero bits as required. (If you do want bit
504fields, there is L<perlfunc/vec>. Or you could implement bit field
505handling at the character string level, using split, substr, and
506concatenation on unpacked bit strings.)
507
508To illustrate unpacking for bit strings, we'll decompose a simple
509status register (a "-" stands for a "reserved" bit):
510
511 +-----------------+-----------------+
512 | S Z - A - P - C | - - - - O D I T |
513 +-----------------+-----------------+
514 MSB LSB MSB LSB
515
516Converting these two bytes to a string can be done with the unpack
517template C<'b16'>. To obtain the individual bit values from the bit
47f22e19 518string we use C<split> with the "empty" separator pattern which dissects
34babc16 519into individual characters. Bit values from the "reserved" positions are
520simply assigned to C<undef>, a convenient notation for "I don't care where
521this goes".
522
523 ($carry, undef, $parity, undef, $auxcarry, undef, $sign,
524 $trace, $interrupt, $direction, $overflow) =
47f22e19 525 split( //, unpack( 'b16', $status ) );
34babc16 526
527We could have used an unpack template C<'b12'> just as well, since the
528last 4 bits can be ignored anyway.
529
530
531=head2 Uuencoding
532
533Another odd-man-out in the template alphabet is C<u>, which packs an
534"uuencoded string". ("uu" is short for Unix-to-Unix.) Chances are that
535you won't ever need this encoding technique which was invented to overcome
536the shortcomings of old-fashioned transmission mediums that do not support
537other than simple ASCII data. The essential recipe is simple: Take three
538bytes, or 24 bits. Split them into 4 six-packs, adding a space (0x20) to
539each. Repeat until all of the data is blended. Fold groups of 4 bytes into
540lines no longer than 60 and garnish them in front with the original byte count
541(incremented by 0x20) and a C<"\n"> at the end. - The C<pack> chef will
542prepare this for you, a la minute, when you select pack code C<u> on the menu:
543
544 my $uubuf = pack( 'u', $bindat );
545
546A repeat count after C<u> sets the number of bytes to put into an
547uuencoded line, which is the maximum of 45 by default, but could be
548set to some (smaller) integer multiple of three. C<unpack> simply ignores
549the repeat count.
550
551
552=head2 Doing Sums
553
554An even stranger template code is C<%>E<lt>I<number>E<gt>. First, because
555it's used as a prefix to some other template code. Second, because it
556cannot be used in C<pack> at all, and third, in C<unpack>, doesn't return the
557data as defined by the template code it precedes. Instead it'll give you an
558integer of I<number> bits that is computed from the data value by
559doing sums. For numeric unpack codes, no big feat is achieved:
560
561 my $buf = pack( 'iii', 100, 20, 3 );
562 print unpack( '%32i3', $buf ), "\n"; # prints 123
563
564For string values, C<%> returns the sum of the byte values saving
565you the trouble of a sum loop with C<substr> and C<ord>:
566
567 print unpack( '%32A*', "\x01\x10" ), "\n"; # prints 17
568
569Although the C<%> code is documented as returning a "checksum":
570don't put your trust in such values! Even when applied to a small number
571of bytes, they won't guarantee a noticeable Hamming distance.
572
573In connection with C<b> or C<B>, C<%> simply adds bits, and this can be put
574to good use to count set bits efficiently:
575
576 my $bitcount = unpack( '%32b*', $mask );
577
578And an even parity bit can be determined like this:
579
580 my $evenparity = unpack( '%1b*', $mask );
581
582
583=head2 Unicode
584
585Unicode is a character set that can represent most characters in most of
586the world's languages, providing room for over one million different
587characters. Unicode 3.1 specifies 94,140 characters: The Basic Latin
588characters are assigned to the numbers 0 - 127. The Latin-1 Supplement with
589characters that are used in several European languages is in the next
590range, up to 255. After some more Latin extensions we find the character
47b6252e 591sets from languages using non-Roman alphabets, interspersed with a
34babc16 592variety of symbol sets such as currency symbols, Zapf Dingbats or Braille.
593(You might want to visit L<www.unicode.org> for a look at some of
594them - my personal favourites are Telugu and Kannada.)
595
596The Unicode character sets associates characters with integers. Encoding
597these numbers in an equal number of bytes would more than double the
47b6252e 598requirements for storing texts written in Latin alphabets.
34babc16 599The UTF-8 encoding avoids this by storing the most common (from a western
600point of view) characters in a single byte while encoding the rarer
601ones in three or more bytes.
602
603So what has this got to do with C<pack>? Well, if you want to convert
604between a Unicode number and its UTF-8 representation you can do so by
605using template code C<U>. As an example, let's produce the UTF-8
606representation of the Euro currency symbol (code number 0x20AC):
607
608 $UTF8{Euro} = pack( 'U', 0x20AC );
609
610Inspecting C<$UTF8{Euro}> shows that it contains 3 bytes: "\xe2\x82\xac". The
611round trip can be completed with C<unpack>:
612
613 $Unicode{Euro} = unpack( 'U', $UTF8{Euro} );
614
615Usually you'll want to pack or unpack UTF-8 strings:
616
617 # pack and unpack the Hebrew alphabet
618 my $alefbet = pack( 'U*', 0x05d0..0x05ea );
619 my @hebrew = unpack( 'U*', $utf );
620
621
47f22e19 622=head2 Another Portable Binary Encoding
623
624The pack code C<w> has been added to support a portable binary data
625encoding scheme that goes way beyond simple integers. (Details can
626be found at L<Casbah.org>, the Scarab project.) A BER (Binary Encoded
627Representation) compressed unsigned integer stores base 128
628digits, most significant digit first, with as few digits as possible.
629Bit eight (the high bit) is set on each byte except the last. There
630is no size limit to BER encoding, but Perl won't go to extremes.
631
632 my $berbuf = pack( 'w*', 1, 128, 128+1, 128*128+127 );
633
634A hex dump of C<$berbuf>, with spaces inserted at the right places,
635shows 01 8100 8101 81807F. Since the last byte is always less than
636128, C<unpack> knows where to stop.
637
34babc16 638
639=head1 Lengths and Widths
640
641=head2 String Lengths
642
643In the previous section we've seen a network message that was constructed
644by prefixing the binary message length to the actual message. You'll find
645that packing a length followed by so many bytes of data is a
646frequently used recipe since appending a null byte won't work
47b6252e 647if a null byte may be part of the data. Here is an example where both
34babc16 648techniques are used: after two null terminated strings with source and
649destination address, a Short Message (to a mobile phone) is sent after
650a length byte:
651
652 my $msg = pack( 'Z*Z*CA*', $src, $dst, length( $sm ), $sm );
653
654Unpacking this message can be done with the same template:
655
656 ( $src, $dst, $len, $sm ) = unpack( 'Z*Z*CA*', $msg );
657
47b6252e 658There's a subtle trap lurking in the offing: Adding another field after
34babc16 659the Short Message (in variable C<$sm>) is all right when packing, but this
660cannot be unpacked naively:
661
662 # pack a message
663 my $msg = pack( 'Z*Z*CA*C', $src, $dst, length( $sm ), $sm, $prio );
7207e29d 664
34babc16 665 # unpack fails - $prio remains undefined!
666 ( $src, $dst, $len, $sm, $prio ) = unpack( 'Z*Z*CA*C', $msg );
667
668The pack code C<A*> gobbles up all remaining bytes, and C<$prio> remains
669undefined! Before we let disappointment dampen the morale: Perl's got
670the trump card to make this trick too, just a little further up the sleeve.
671Watch this:
672
673 # pack a message: ASCIIZ, ASCIIZ, length/string, byte
674 my $msg = pack( 'Z* Z* C/A* C', $src, $dst, $sm, $prio );
675
676 # unpack
677 ( $src, $dst, $sm, $prio ) = unpack( 'Z* Z* C/A* C', $msg );
678
679Combining two pack codes with a slash (C</>) associates them with a single
680value from the argument list. In C<pack>, the length of the argument is
681taken and packed according to the first code while the argument itself
682is added after being converted with the template code after the slash.
683This saves us the trouble of inserting the C<length> call, but it is
684in C<unpack> where we really score: The value of the length byte marks the
685end of the string to be taken from the buffer. Since this combination
f8b4d74f 686doesn't make sense except when the second pack code isn't C<a*>, C<A*>
34babc16 687or C<Z*>, Perl won't let you.
688
689The pack code preceding C</> may be anything that's fit to represent a
690number: All the numeric binary pack codes, and even text codes such as
691C<A4> or C<Z*>:
692
693 # pack/unpack a string preceded by its length in ASCII
694 my $buf = pack( 'A4/A*', "Humpty-Dumpty" );
695 # unpack $buf: '13 Humpty-Dumpty'
696 my $txt = unpack( 'A4/A*', $buf );
697
47b6252e 698C</> is not implemented in Perls before 5.6, so if your code is required to
699work on older Perls you'll need to C<unpack( 'Z* Z* C')> to get the length,
700then use it to make a new unpack string. For example
701
702 # pack a message: ASCIIZ, ASCIIZ, length, string, byte (5.005 compatible)
703 my $msg = pack( 'Z* Z* C A* C', $src, $dst, length $sm, $sm, $prio );
704
705 # unpack
706 ( undef, undef, $len) = unpack( 'Z* Z* C', $msg );
707 ($src, $dst, $sm, $prio) = unpack ( "Z* Z* x A$len C", $msg );
708
709But that second C<unpack> is rushing ahead. It isn't using a simple literal
710string for the template. So maybe we should introduce...
34babc16 711
712=head2 Dynamic Templates
713
714So far, we've seen literals used as templates. If the list of pack
715items doesn't have fixed length, an expression constructing the
716template has to be used. Here's an example:
717To store named string values in a way that can be conveniently parsed
718by a C program, we create a sequence of names and null terminated ASCII
719strings, with C<=> between the name and the value, followed by an
720additional delimiting null byte. Here's how:
721
722 my $env = pack( 'A*A*Z*' x keys( %Env ) . 'C',
47f22e19 723 map( { ( $_, '=', $Env{$_} ) } keys( %Env ) ), 0 );
724
725Let's examine the cogs of this byte mill, one by one. There's the C<map>
726call, creating the items we intend to stuff into the C<$env> buffer:
727to each key (in C<$_>) it adds the C<=> separator and the hash entry value.
728Each triplet is packed with the template code sequence C<A*A*Z*> that
729is multiplied with the number of keys. (Yes, that's what the C<keys>
fe854a6f 730function returns in scalar context.) To get the very last null byte,
47f22e19 731we add a C<0> at the end of the C<pack> list, to be packed with C<C>.
732(Attentive readers may have noticed that we could have omitted the 0.)
34babc16 733
734For the reverse operation, we'll have to determine the number of items
735in the buffer before we can let C<unpack> rip it apart:
736
47b6252e 737 my $n = $env =~ tr/\0// - 1;
47f22e19 738 my %env = map( split( /=/, $_ ), unpack( 'Z*' x $n, $env ) );
34babc16 739
47b6252e 740The C<tr> counts the null bytes. The C<unpack> call returns a list of
47f22e19 741name-value pairs each of which is taken apart in the C<map> block.
34babc16 742
743
744=head1 Packing and Unpacking C Structures
745
746In previous sections we have seen how to pack numbers and character
747strings. If it were not for a couple of snags we could conclude this
748section right away with the terse remark that C structures don't
749contain anything else, and therefore you already know all there is to it.
750Sorry, no: read on, please.
751
752=head2 The Alignment Pit
753
754In the consideration of speed against memory requirements the balance
755has been tilted in favor of faster execution. This has influenced the
756way C compilers allocate memory for structures: On architectures
757where a 16-bit or 32-bit operand can be moved faster between places in
758memory, or to or from a CPU register, if it is aligned at an even or
759multiple-of-four or even at a multiple-of eight address, a C compiler
760will give you this speed benefit by stuffing extra bytes into structures.
761If you don't cross the C shoreline this is not likely to cause you any
47b6252e 762grief (although you should care when you design large data structures,
763or you want your code to be portable between architectures (you do want
764that, don't you?)).
34babc16 765
766To see how this affects C<pack> and C<unpack>, we'll compare these two
767C structures:
768
769 typedef struct {
770 char c1;
771 short s;
772 char c2;
773 long l;
774 } gappy_t;
775
776 typedef struct {
777 long l;
778 short s;
779 char c1;
780 char c2;
781 } dense_t;
782
783Typically, a C compiler allocates 12 bytes to a C<gappy_t> variable, but
784requires only 8 bytes for a C<dense_t>. After investigating this further,
785we can draw memory maps, showing where the extra 4 bytes are hidden:
786
787 0 +4 +8 +12
788 +--+--+--+--+--+--+--+--+--+--+--+--+
789 |c1|xx| s |c2|xx|xx|xx| l | xx = fill byte
790 +--+--+--+--+--+--+--+--+--+--+--+--+
791 gappy_t
792
793 0 +4 +8
794 +--+--+--+--+--+--+--+--+
795 | l | h |c1|c2|
796 +--+--+--+--+--+--+--+--+
797 dense_t
798
799And that's where the first quirk strikes: C<pack> and C<unpack>
800templates have to be stuffed with C<x> codes to get those extra fill bytes.
801
802The natural question: "Why can't Perl compensate for the gaps?" warrants
803an answer. One good reason is that C compilers might provide (non-ANSI)
804extensions permitting all sorts of fancy control over the way structures
805are aligned, even at the level of an individual structure field. And, if
806this were not enough, there is an insidious thing called C<union> where
807the amount of fill bytes cannot be derived from the alignment of the next
808item alone.
809
810OK, so let's bite the bullet. Here's one way to get the alignment right
811by inserting template codes C<x>, which don't take a corresponding item
812from the list:
813
814 my $gappy = pack( 'cxs cxxx l!', $c1, $s, $c2, $l );
815
816Note the C<!> after C<l>: We want to make sure that we pack a long
47b6252e 817integer as it is compiled by our C compiler. And even now, it will only
818work for the platforms where the compiler aligns things as above.
819And somebody somewhere has a platform where it doesn't.
820[Probably a Cray, where C<short>s, C<int>s and C<long>s are all 8 bytes. :-)]
34babc16 821
822Counting bytes and watching alignments in lengthy structures is bound to
823be a drag. Isn't there a way we can create the template with a simple
824program? Here's a C program that does the trick:
825
826 #include <stdio.h>
827 #include <stddef.h>
828
829 typedef struct {
830 char fc1;
831 short fs;
832 char fc2;
833 long fl;
834 } gappy_t;
835
836 #define Pt(struct,field,tchar) \
837 printf( "@%d%s ", offsetof(struct,field), # tchar );
838
839 int main(){
840 Pt( gappy_t, fc1, c );
841 Pt( gappy_t, fs, s! );
842 Pt( gappy_t, fc2, c );
843 Pt( gappy_t, fl, l! );
844 printf( "\n" );
845 }
846
847The output line can be used as a template in a C<pack> or C<unpack> call:
848
849 my $gappy = pack( '@0c @2s! @4c @8l!', $c1, $s, $c2, $l );
850
851Gee, yet another template code - as if we hadn't plenty. But
852C<@> saves our day by enabling us to specify the offset from the beginning
853of the pack buffer to the next item: This is just the value
854the C<offsetof> macro (defined in C<E<lt>stddef.hE<gt>>) returns when
855given a C<struct> type and one of its field names ("member-designator" in
856C standardese).
857
858
859=head2 Alignment, Take 2
860
861I'm afraid that we're not quite through with the alignment catch yet. The
862hydra raises another ugly head when you pack arrays of structures:
863
864 typedef struct {
865 short count;
866 char glyph;
867 } cell_t;
868
869 typedef cell_t buffer_t[BUFLEN];
870
871Where's the catch? Padding is neither required before the first field C<count>,
872nor between this and the next field C<glyph>, so why can't we simply pack
873like this:
874
875 # something goes wrong here:
876 pack( 's!a' x @buffer,
877 map{ ( $_->{count}, $_->{glyph} ) } @buffer );
878
879This packs C<3*@buffer> bytes, but it turns out that the size of
880C<buffer_t> is four times C<BUFLEN>! The moral of the story is that
881the required alignment of a structure or array is propagated to the
882next higher level where we have to consider padding I<at the end>
883of each component as well. Thus the correct template is:
884
885 pack( 's!ax' x @buffer,
886 map{ ( $_->{count}, $_->{glyph} ) } @buffer );
887
47b6252e 888=head2 Alignment, Take 3
889
890And even if you take all the above into account, ANSI still lets this:
891
892 typedef struct {
893 char foo[2];
894 } foo_t;
34babc16 895
47b6252e 896vary in size. The alignment constraint of the structure can be greater than
897any of its elements. [And if you think that this doesn't affect anything
898common, dismember the next cellphone that you see. Many have ARM cores, and
899the ARM structure rules make C<sizeof (foo_t)> == 4]
34babc16 900
901=head2 Pointers for How to Use Them
902
903The title of this section indicates the second problem you may run into
904sooner or later when you pack C structures. If the function you intend
905to call expects a, say, C<void *> value, you I<cannot> simply take
906a reference to a Perl variable. (Although that value certainly is a
907memory address, it's not the address where the variable's contents are
908stored.)
909
910Template code C<P> promises to pack a "pointer to a fixed length string".
911Isn't this what we want? Let's try:
912
913 # allocate some storage and pack a pointer to it
914 my $memory = "\x00" x $size;
915 my $memptr = pack( 'P', $memory );
916
917But wait: doesn't C<pack> just return a sequence of bytes? How can we pass this
918string of bytes to some C code expecting a pointer which is, after all,
919nothing but a number? The answer is simple: We have to obtain the numeric
920address from the bytes returned by C<pack>.
921
922 my $ptr = unpack( 'L!', $memptr );
923
924Obviously this assumes that it is possible to typecast a pointer
925to an unsigned long and vice versa, which frequently works but should not
926be taken as a universal law. - Now that we have this pointer the next question
927is: How can we put it to good use? We need a call to some C function
928where a pointer is expected. The read(2) system call comes to mind:
929
930 ssize_t read(int fd, void *buf, size_t count);
931
932After reading L<perlfunc> explaining how to use C<syscall> we can write
933this Perl function copying a file to standard output:
934
935 require 'syscall.ph';
936 sub cat($){
937 my $path = shift();
938 my $size = -s $path;
939 my $memory = "\x00" x $size; # allocate some memory
940 my $ptr = unpack( 'L', pack( 'P', $memory ) );
941 open( F, $path ) || die( "$path: cannot open ($!)\n" );
942 my $fd = fileno(F);
943 my $res = syscall( &SYS_read, fileno(F), $ptr, $size );
944 print $memory;
945 close( F );
946 }
947
948This is neither a specimen of simplicity nor a paragon of portability but
949it illustrates the point: We are able to sneak behind the scenes and
950access Perl's otherwise well-guarded memory! (Important note: Perl's
951C<syscall> does I<not> require you to construct pointers in this roundabout
952way. You simply pass a string variable, and Perl forwards the address.)
953
954How does C<unpack> with C<P> work? Imagine some pointer in the buffer
955about to be unpacked: If it isn't the null pointer (which will smartly
956produce the C<undef> value) we have a start address - but then what?
957Perl has no way of knowing how long this "fixed length string" is, so
958it's up to you to specify the actual size as an explicit length after C<P>.
959
960 my $mem = "abcdefghijklmn";
961 print unpack( 'P5', pack( 'P', $mem ) ); # prints "abcde"
962
963As a consequence, C<pack> ignores any number or C<*> after C<P>.
964
965
966Now that we have seen C<P> at work, we might as well give C<p> a whirl.
967Why do we need a second template code for packing pointers at all? The
968answer lies behind the simple fact that an C<unpack> with C<p> promises
969a null-terminated string starting at the address taken from the buffer,
970and that implies a length for the data item to be returned:
971
972 my $buf = pack( 'p', "abc\x00efhijklmn" );
973 print unpack( 'p', $buf ); # prints "abc"
974
975
976
977Albeit this is apt to be confusing: As a consequence of the length being
978implied by the string's length, a number after pack code C<p> is a repeat
979count, not a length as after C<P>.
980
981
982Using C<pack(..., $x)> with C<P> or C<p> to get the address where C<$x> is
983actually stored must be used with circumspection. Perl's internal machinery
984considers the relation between a variable and that address as its very own
985private matter and doesn't really care that we have obtained a copy. Therefore:
986
987=over 4
988
989=item *
990
991Do not use C<pack> with C<p> or C<P> to obtain the address of variable
992that's bound to go out of scope (and thereby freeing its memory) before you
993are done with using the memory at that address.
994
995=item *
996
997Be very careful with Perl operations that change the value of the
998variable. Appending something to the variable, for instance, might require
999reallocation of its storage, leaving you with a pointer into no-man's land.
1000
1001=item *
1002
1003Don't think that you can get the address of a Perl variable
1004when it is stored as an integer or double number! C<pack('P', $x)> will
1005force the variable's internal representation to string, just as if you
1006had written something like C<$x .= ''>.
1007
1008=back
1009
1010It's safe, however, to P- or p-pack a string literal, because Perl simply
1011allocates an anonymous variable.
1012
1013
1014
1015=head1 Pack Recipes
1016
1017Here are a collection of (possibly) useful canned recipes for C<pack>
1018and C<unpack>:
1019
1020 # Convert IP address for socket functions
1021 pack( "C4", split /\./, "123.4.5.6" );
1022
1023 # Count the bits in a chunk of memory (e.g. a select vector)
1024 unpack( '%32b*', $mask );
1025
1026 # Determine the endianness of your system
1027 $is_little_endian = unpack( 'c', pack( 's', 1 ) );
1028 $is_big_endian = unpack( 'xc', pack( 's', 1 ) );
1029
1030 # Determine the number of bits in a native integer
1031 $bits = unpack( '%32I!', ~0 );
1032
1033 # Prepare argument for the nanosleep system call
1034 my $timespec = pack( 'L!L!', $secs, $nanosecs );
1035
f8b4d74f 1036For a simple memory dump we unpack some bytes into just as
1037many pairs of hex digits, and use C<map> to handle the traditional
1038spacing - 16 bytes to a line:
1039
34babc16 1040 my $i;
f8b4d74f 1041 print map { ++$i % 16 ? "$_ " : "$_\n" }
1042 unpack( 'H2' x length( $mem ), $mem ),
1043 length( $mem ) % 16 ? "\n" : '';
34babc16 1044
1045
47f22e19 1046=head1 Funnies Section
1047
1048 # Pulling digits out of nowhere...
1049 print unpack( 'C', pack( 'x' ) ),
1050 unpack( '%B*', pack( 'A' ) ),
1051 unpack( 'H', pack( 'A' ) ),
1052 unpack( 'A', unpack( 'C', pack( 'A' ) ) ), "\n";
1053
1054 # One for the road ;-)
1055 my $advice = pack( 'all u can in a van' );
1056
1057
34babc16 1058=head1 Authors
1059
1060Simon Cozens and Wolfgang Laun.
1061