1PERLPACKTUT(1)         Perl Programmers Reference Guide         PERLPACKTUT(1)
2
3
4

NAME

6       perlpacktut - tutorial on "pack" and "unpack"
7

DESCRIPTION

9       "pack" and "unpack" are two functions for transforming data according
10       to a user-defined template, between the guarded way Perl stores values
11       and some well-defined representation as might be required in the
12       environment of a Perl program. Unfortunately, they're also two of the
13       most misunderstood and most often overlooked functions that Perl
14       provides. This tutorial will demystify them for you.
15

The Basic Principle

17       Most programming languages don't shelter the memory where variables are
18       stored. In C, for instance, you can take the address of some variable,
19       and the "sizeof" operator tells you how many bytes are allocated to the
20       variable. Using the address and the size, you may access the storage to
21       your heart's content.
22
23       In Perl, you just can't access memory at random, but the structural and
24       representational conversion provided by "pack" and "unpack" is an
25       excellent alternative. The "pack" function converts values to a byte
26       sequence containing representations according to a given specification,
27       the so-called "template" argument. "unpack" is the reverse process,
28       deriving some values from the contents of a string of bytes. (Be
29       cautioned, however, that not all that has been packed together can be
30       neatly unpacked - a very common experience as seasoned travellers are
31       likely to confirm.)
32
33       Why, you may ask, would you need a chunk of memory containing some
34       values in binary representation? One good reason is input and output
35       accessing some file, a device, or a network connection, whereby this
36       binary representation is either forced on you or will give you some
37       benefit in processing. Another cause is passing data to some system
38       call that is not available as a Perl function: "syscall" requires you
39       to provide parameters stored in the way it happens in a C program. Even
40       text processing (as shown in the next section) may be simplified with
41       judicious usage of these two functions.
42
43       To see how (un)packing works, we'll start with a simple template code
44       where the conversion is in low gear: between the contents of a byte
45       sequence and a string of hexadecimal digits. Let's use "unpack", since
46       this is likely to remind you of a dump program, or some desperate last
47       message unfortunate programs are wont to throw at you before they
48       expire into the wild blue yonder. Assuming that the variable $mem holds
49       a sequence of bytes that we'd like to inspect without assuming anything
50       about its meaning, we can write
51
52          my( $hex ) = unpack( 'H*', $mem );
53          print "$hex\n";
54
55       whereupon we might see something like this, with each pair of hex
56       digits corresponding to a byte:
57
58          41204d414e204120504c414e20412043414e414c2050414e414d41
59
60       What was in this chunk of memory? Numbers, characters, or a mixture of
61       both? Assuming that we're on a computer where ASCII (or some similar)
62       encoding is used: hexadecimal values in the range 0x40 - 0x5A indicate
63       an uppercase letter, and 0x20 encodes a space. So we might assume it is
64       a piece of text, which some are able to read like a tabloid; but others
65       will have to get hold of an ASCII table and relive that firstgrader
66       feeling. Not caring too much about which way to read this, we note that
67       "unpack" with the template code "H" converts the contents of a sequence
68       of bytes into the customary hexadecimal notation. Since "a sequence of"
69       is a pretty vague indication of quantity, "H" has been defined to
70       convert just a single hexadecimal digit unless it is followed by a
71       repeat count. An asterisk for the repeat count means to use whatever
72       remains.
73
74       The inverse operation - packing byte contents from a string of
75       hexadecimal digits - is just as easily written. For instance:
76
77          my $s = pack( 'H2' x 10, map { "3$_" } ( 0..9 ) );
78          print "$s\n";
79
80       Since we feed a list of ten 2-digit hexadecimal strings to "pack", the
81       pack template should contain ten pack codes. If this is run on a
82       computer with ASCII character coding, it will print 0123456789.
83

Packing Text

85       Let's suppose you've got to read in a data file like this:
86
87           Date      |Description                | Income|Expenditure
88           01/24/2001 Ahmed's Camel Emporium                  1147.99
89           01/28/2001 Flea spray                                24.99
90           01/29/2001 Camel rides to tourists      235.00
91
92       How do we do it? You might think first to use "split"; however, since
93       "split" collapses blank fields, you'll never know whether a record was
94       income or expenditure. Oops. Well, you could always use "substr":
95
96           while (<>) {
97               my $date   = substr($_,  0, 11);
98               my $desc   = substr($_, 12, 27);
99               my $income = substr($_, 40,  7);
100               my $expend = substr($_, 52,  7);
101               ...
102           }
103
104       It's not really a barrel of laughs, is it? In fact, it's worse than it
105       may seem; the eagle-eyed may notice that the first field should only be
106       10 characters wide, and the error has propagated right through the
107       other numbers - which we've had to count by hand. So it's error-prone
108       as well as horribly unfriendly.
109
110       Or maybe we could use regular expressions:
111
112           while (<>) {
113               my($date, $desc, $income, $expend) =
114                   m|(\d\d/\d\d/\d{4}) (.{27}) (.{7})(.*)|;
115               ...
116           }
117
118       Urgh. Well, it's a bit better, but - well, would you want to maintain
119       that?
120
121       Hey, isn't Perl supposed to make this sort of thing easy? Well, it
122       does, if you use the right tools. "pack" and "unpack" are designed to
123       help you out when dealing with fixed-width data like the above. Let's
124       have a look at a solution with "unpack":
125
126           while (<>) {
127               my($date, $desc, $income, $expend) = unpack("A10xA27xA7A*", $_);
128               ...
129           }
130
131       That looks a bit nicer; but we've got to take apart that weird
132       template.  Where did I pull that out of?
133
134       OK, let's have a look at some of our data again; in fact, we'll include
135       the headers, and a handy ruler so we can keep track of where we are.
136
137                    1         2         3         4         5
138           1234567890123456789012345678901234567890123456789012345678
139           Date      |Description                | Income|Expenditure
140           01/28/2001 Flea spray                                24.99
141           01/29/2001 Camel rides to tourists      235.00
142
143       From this, we can see that the date column stretches from column 1 to
144       column 10 - ten characters wide. The "pack"-ese for "character" is "A",
145       and ten of them are "A10". So if we just wanted to extract the dates,
146       we could say this:
147
148           my($date) = unpack("A10", $_);
149
150       OK, what's next? Between the date and the description is a blank
151       column; we want to skip over that. The "x" template means "skip
152       forward", so we want one of those. Next, we have another batch of
153       characters, from 12 to 38. That's 27 more characters, hence "A27".
154       (Don't make the fencepost error - there are 27 characters between 12
155       and 38, not 26. Count 'em!)
156
157       Now we skip another character and pick up the next 7 characters:
158
159           my($date,$description,$income) = unpack("A10xA27xA7", $_);
160
161       Now comes the clever bit. Lines in our ledger which are just income and
162       not expenditure might end at column 46. Hence, we don't want to tell
163       our "unpack" pattern that we need to find another 12 characters; we'll
164       just say "if there's anything left, take it". As you might guess from
165       regular expressions, that's what the "*" means: "use everything
166       remaining".
167
168       ·  Be warned, though, that unlike regular expressions, if the "unpack"
169          template doesn't match the incoming data, Perl will scream and die.
170
171       Hence, putting it all together:
172
173           my($date,$description,$income,$expend) = unpack("A10xA27xA7xA*", $_);
174
175       Now, that's our data parsed. I suppose what we might want to do now is
176       total up our income and expenditure, and add another line to the end of
177       our ledger - in the same format - saying how much we've brought in and
178       how much we've spent:
179
180           while (<>) {
181               my($date, $desc, $income, $expend) = unpack("A10xA27xA7xA*", $_);
182               $tot_income += $income;
183               $tot_expend += $expend;
184           }
185
186           $tot_income = sprintf("%.2f", $tot_income); # Get them into
187           $tot_expend = sprintf("%.2f", $tot_expend); # "financial" format
188
189           $date = POSIX::strftime("%m/%d/%Y", localtime);
190
191           # OK, let's go:
192
193           print pack("A10xA27xA7xA*", $date, "Totals", $tot_income, $tot_expend);
194
195       Oh, hmm. That didn't quite work. Let's see what happened:
196
197           01/24/2001 Ahmed's Camel Emporium                   1147.99
198           01/28/2001 Flea spray                                 24.99
199           01/29/2001 Camel rides to tourists     1235.00
200           03/23/2001Totals                     1235.001172.98
201
202       OK, it's a start, but what happened to the spaces? We put "x", didn't
203       we? Shouldn't it skip forward? Let's look at what "pack" in perlfunc
204       says:
205
206           x   A null byte.
207
208       Urgh. No wonder. There's a big difference between "a null byte",
209       character zero, and "a space", character 32. Perl's put something
210       between the date and the description - but unfortunately, we can't see
211       it!
212
213       What we actually need to do is expand the width of the fields. The "A"
214       format pads any non-existent characters with spaces, so we can use the
215       additional spaces to line up our fields, like this:
216
217           print pack("A11 A28 A8 A*", $date, "Totals", $tot_income, $tot_expend);
218
219       (Note that you can put spaces in the template to make it more readable,
220       but they don't translate to spaces in the output.) Here's what we got
221       this time:
222
223           01/24/2001 Ahmed's Camel Emporium                   1147.99
224           01/28/2001 Flea spray                                 24.99
225           01/29/2001 Camel rides to tourists     1235.00
226           03/23/2001 Totals                      1235.00 1172.98
227
228       That's a bit better, but we still have that last column which needs to
229       be moved further over. There's an easy way to fix this up:
230       unfortunately, we can't get "pack" to right-justify our fields, but we
231       can get "sprintf" to do it:
232
233           $tot_income = sprintf("%.2f", $tot_income);
234           $tot_expend = sprintf("%12.2f", $tot_expend);
235           $date = POSIX::strftime("%m/%d/%Y", localtime);
236           print pack("A11 A28 A8 A*", $date, "Totals", $tot_income, $tot_expend);
237
238       This time we get the right answer:
239
240           01/28/2001 Flea spray                                 24.99
241           01/29/2001 Camel rides to tourists     1235.00
242           03/23/2001 Totals                      1235.00      1172.98
243
244       So that's how we consume and produce fixed-width data. Let's recap what
245       we've seen of "pack" and "unpack" so far:
246
247       ·  Use "pack" to go from several pieces of data to one fixed-width
248          version; use "unpack" to turn a fixed-width-format string into
249          several pieces of data.
250
251       ·  The pack format "A" means "any character"; if you're "pack"ing and
252          you've run out of things to pack, "pack" will fill the rest up with
253          spaces.
254
255       ·  "x" means "skip a byte" when "unpack"ing; when "pack"ing, it means
256          "introduce a null byte" - that's probably not what you mean if
257          you're dealing with plain text.
258
259       ·  You can follow the formats with numbers to say how many characters
260          should be affected by that format: "A12" means "take 12 characters";
261          "x6" means "skip 6 bytes" or "character 0, 6 times".
262
263       ·  Instead of a number, you can use "*" to mean "consume everything
264          else left".
265
266          Warning: when packing multiple pieces of data, "*" only means
267          "consume all of the current piece of data". That's to say
268
269              pack("A*A*", $one, $two)
270
271          packs all of $one into the first "A*" and then all of $two into the
272          second. This is a general principle: each format character
273          corresponds to one piece of data to be "pack"ed.
274

Packing Numbers

276       So much for textual data. Let's get onto the meaty stuff that "pack"
277       and "unpack" are best at: handling binary formats for numbers. There
278       is, of course, not just one binary format  - life would be too simple -
279       but Perl will do all the finicky labor for you.
280
281   Integers
282       Packing and unpacking numbers implies conversion to and from some
283       specific binary representation. Leaving floating point numbers aside
284       for the moment, the salient properties of any such representation are:
285
286       ·   the number of bytes used for storing the integer,
287
288       ·   whether the contents are interpreted as a signed or unsigned
289           number,
290
291       ·   the byte ordering: whether the first byte is the least or most
292           significant byte (or: little-endian or big-endian, respectively).
293
294       So, for instance, to pack 20302 to a signed 16 bit integer in your
295       computer's representation you write
296
297          my $ps = pack( 's', 20302 );
298
299       Again, the result is a string, now containing 2 bytes. If you print
300       this string (which is, generally, not recommended) you might see "ON"
301       or "NO" (depending on your system's byte ordering) - or something
302       entirely different if your computer doesn't use ASCII character
303       encoding.  Unpacking $ps with the same template returns the original
304       integer value:
305
306          my( $s ) = unpack( 's', $ps );
307
308       This is true for all numeric template codes. But don't expect miracles:
309       if the packed value exceeds the allotted byte capacity, high order bits
310       are silently discarded, and unpack certainly won't be able to pull them
311       back out of some magic hat. And, when you pack using a signed template
312       code such as "s", an excess value may result in the sign bit getting
313       set, and unpacking this will smartly return a negative value.
314
315       16 bits won't get you too far with integers, but there is "l" and "L"
316       for signed and unsigned 32-bit integers. And if this is not enough and
317       your system supports 64 bit integers you can push the limits much
318       closer to infinity with pack codes "q" and "Q". A notable exception is
319       provided by pack codes "i" and "I" for signed and unsigned integers of
320       the "local custom" variety: Such an integer will take up as many bytes
321       as a local C compiler returns for "sizeof(int)", but it'll use at least
322       32 bits.
323
324       Each of the integer pack codes "sSlLqQ" results in a fixed number of
325       bytes, no matter where you execute your program. This may be useful for
326       some applications, but it does not provide for a portable way to pass
327       data structures between Perl and C programs (bound to happen when you
328       call XS extensions or the Perl function "syscall"), or when you read or
329       write binary files. What you'll need in this case are template codes
330       that depend on what your local C compiler compiles when you code
331       "short" or "unsigned long", for instance. These codes and their
332       corresponding byte lengths are shown in the table below.  Since the C
333       standard leaves much leeway with respect to the relative sizes of these
334       data types, actual values may vary, and that's why the values are given
335       as expressions in C and Perl. (If you'd like to use values from %Config
336       in your program you have to import it with "use Config".)
337
338          signed unsigned  byte length in C   byte length in Perl
339            s!     S!      sizeof(short)      $Config{shortsize}
340            i!     I!      sizeof(int)        $Config{intsize}
341            l!     L!      sizeof(long)       $Config{longsize}
342            q!     Q!      sizeof(long long)  $Config{longlongsize}
343
344       The "i!" and "I!" codes aren't different from "i" and "I"; they are
345       tolerated for completeness' sake.
346
347   Unpacking a Stack Frame
348       Requesting a particular byte ordering may be necessary when you work
349       with binary data coming from some specific architecture whereas your
350       program could run on a totally different system. As an example, assume
351       you have 24 bytes containing a stack frame as it happens on an Intel
352       8086:
353
354             +---------+        +----+----+               +---------+
355        TOS: |   IP    |  TOS+4:| FL | FH | FLAGS  TOS+14:|   SI    |
356             +---------+        +----+----+               +---------+
357             |   CS    |        | AL | AH | AX            |   DI    |
358             +---------+        +----+----+               +---------+
359                                | BL | BH | BX            |   BP    |
360                                +----+----+               +---------+
361                                | CL | CH | CX            |   DS    |
362                                +----+----+               +---------+
363                                | DL | DH | DX            |   ES    |
364                                +----+----+               +---------+
365
366       First, we note that this time-honored 16-bit CPU uses little-endian
367       order, and that's why the low order byte is stored at the lower
368       address. To unpack such a (unsigned) short we'll have to use code "v".
369       A repeat count unpacks all 12 shorts:
370
371          my( $ip, $cs, $flags, $ax, $bx, $cd, $dx, $si, $di, $bp, $ds, $es ) =
372            unpack( 'v12', $frame );
373
374       Alternatively, we could have used "C" to unpack the individually
375       accessible byte registers FL, FH, AL, AH, etc.:
376
377          my( $fl, $fh, $al, $ah, $bl, $bh, $cl, $ch, $dl, $dh ) =
378            unpack( 'C10', substr( $frame, 4, 10 ) );
379
380       It would be nice if we could do this in one fell swoop: unpack a short,
381       back up a little, and then unpack 2 bytes. Since Perl is nice, it
382       proffers the template code "X" to back up one byte. Putting this all
383       together, we may now write:
384
385          my( $ip, $cs,
386              $flags,$fl,$fh,
387              $ax,$al,$ah, $bx,$bl,$bh, $cx,$cl,$ch, $dx,$dl,$dh,
388              $si, $di, $bp, $ds, $es ) =
389          unpack( 'v2' . ('vXXCC' x 5) . 'v5', $frame );
390
391       (The clumsy construction of the template can be avoided - just read
392       on!)
393
394       We've taken some pains to construct the template so that it matches the
395       contents of our frame buffer. Otherwise we'd either get undefined
396       values, or "unpack" could not unpack all. If "pack" runs out of items,
397       it will supply null strings (which are coerced into zeroes whenever the
398       pack code says so).
399
400   How to Eat an Egg on a Net
401       The pack code for big-endian (high order byte at the lowest address) is
402       "n" for 16 bit and "N" for 32 bit integers. You use these codes if you
403       know that your data comes from a compliant architecture, but,
404       surprisingly enough, you should also use these pack codes if you
405       exchange binary data, across the network, with some system that you
406       know next to nothing about. The simple reason is that this order has
407       been chosen as the network order, and all standard-fearing programs
408       ought to follow this convention. (This is, of course, a stern backing
409       for one of the Lilliputian parties and may well influence the political
410       development there.) So, if the protocol expects you to send a message
411       by sending the length first, followed by just so many bytes, you could
412       write:
413
414          my $buf = pack( 'N', length( $msg ) ) . $msg;
415
416       or even:
417
418          my $buf = pack( 'NA*', length( $msg ), $msg );
419
420       and pass $buf to your send routine. Some protocols demand that the
421       count should include the length of the count itself: then just add 4 to
422       the data length. (But make sure to read "Lengths and Widths" before you
423       really code this!)
424
425   Byte-order modifiers
426       In the previous sections we've learned how to use "n", "N", "v" and "V"
427       to pack and unpack integers with big- or little-endian byte-order.
428       While this is nice, it's still rather limited because it leaves out all
429       kinds of signed integers as well as 64-bit integers. For example, if
430       you wanted to unpack a sequence of signed big-endian 16-bit integers in
431       a platform-independent way, you would have to write:
432
433          my @data = unpack 's*', pack 'S*', unpack 'n*', $buf;
434
435       This is ugly. As of Perl 5.9.2, there's a much nicer way to express
436       your desire for a certain byte-order: the ">" and "<" modifiers.  ">"
437       is the big-endian modifier, while "<" is the little-endian modifier.
438       Using them, we could rewrite the above code as:
439
440          my @data = unpack 's>*', $buf;
441
442       As you can see, the "big end" of the arrow touches the "s", which is a
443       nice way to remember that ">" is the big-endian modifier. The same
444       obviously works for "<", where the "little end" touches the code.
445
446       You will probably find these modifiers even more useful if you have to
447       deal with big- or little-endian C structures. Be sure to read "Packing
448       and Unpacking C Structures" for more on that.
449
450   Floating point Numbers
451       For packing floating point numbers you have the choice between the pack
452       codes "f", "d", "F" and "D". "f" and "d" pack into (or unpack from)
453       single-precision or double-precision representation as it is provided
454       by your system. If your systems supports it, "D" can be used to pack
455       and unpack extended-precision floating point values ("long double"),
456       which can offer even more resolution than "f" or "d". "F" packs an
457       "NV", which is the floating point type used by Perl internally. (There
458       is no such thing as a network representation for reals, so if you want
459       to send your real numbers across computer boundaries, you'd better
460       stick to ASCII representation, unless you're absolutely sure what's on
461       the other end of the line. For the even more adventuresome, you can use
462       the byte-order modifiers from the previous section also on floating
463       point codes.)
464

Exotic Templates

466   Bit Strings
467       Bits are the atoms in the memory world. Access to individual bits may
468       have to be used either as a last resort or because it is the most
469       convenient way to handle your data. Bit string (un)packing converts
470       between strings containing a series of 0 and 1 characters and a
471       sequence of bytes each containing a group of 8 bits. This is almost as
472       simple as it sounds, except that there are two ways the contents of a
473       byte may be written as a bit string. Let's have a look at an annotated
474       byte:
475
476            7 6 5 4 3 2 1 0
477          +-----------------+
478          | 1 0 0 0 1 1 0 0 |
479          +-----------------+
480           MSB           LSB
481
482       It's egg-eating all over again: Some think that as a bit string this
483       should be written "10001100" i.e. beginning with the most significant
484       bit, others insist on "00110001". Well, Perl isn't biased, so that's
485       why we have two bit string codes:
486
487          $byte = pack( 'B8', '10001100' ); # start with MSB
488          $byte = pack( 'b8', '00110001' ); # start with LSB
489
490       It is not possible to pack or unpack bit fields - just integral bytes.
491       "pack" always starts at the next byte boundary and "rounds up" to the
492       next multiple of 8 by adding zero bits as required. (If you do want bit
493       fields, there is "vec" in perlfunc. Or you could implement bit field
494       handling at the character string level, using split, substr, and
495       concatenation on unpacked bit strings.)
496
497       To illustrate unpacking for bit strings, we'll decompose a simple
498       status register (a "-" stands for a "reserved" bit):
499
500          +-----------------+-----------------+
501          | S Z - A - P - C | - - - - O D I T |
502          +-----------------+-----------------+
503           MSB           LSB MSB           LSB
504
505       Converting these two bytes to a string can be done with the unpack
506       template 'b16'. To obtain the individual bit values from the bit string
507       we use "split" with the "empty" separator pattern which dissects into
508       individual characters. Bit values from the "reserved" positions are
509       simply assigned to "undef", a convenient notation for "I don't care
510       where this goes".
511
512          ($carry, undef, $parity, undef, $auxcarry, undef, $zero, $sign,
513           $trace, $interrupt, $direction, $overflow) =
514             split( //, unpack( 'b16', $status ) );
515
516       We could have used an unpack template 'b12' just as well, since the
517       last 4 bits can be ignored anyway.
518
519   Uuencoding
520       Another odd-man-out in the template alphabet is "u", which packs an
521       "uuencoded string". ("uu" is short for Unix-to-Unix.) Chances are that
522       you won't ever need this encoding technique which was invented to
523       overcome the shortcomings of old-fashioned transmission mediums that do
524       not support other than simple ASCII data. The essential recipe is
525       simple: Take three bytes, or 24 bits. Split them into 4 six-packs,
526       adding a space (0x20) to each. Repeat until all of the data is blended.
527       Fold groups of 4 bytes into lines no longer than 60 and garnish them in
528       front with the original byte count (incremented by 0x20) and a "\n" at
529       the end. - The "pack" chef will prepare this for you, a la minute, when
530       you select pack code "u" on the menu:
531
532          my $uubuf = pack( 'u', $bindat );
533
534       A repeat count after "u" sets the number of bytes to put into an
535       uuencoded line, which is the maximum of 45 by default, but could be set
536       to some (smaller) integer multiple of three. "unpack" simply ignores
537       the repeat count.
538
539   Doing Sums
540       An even stranger template code is "%"<number>. First, because it's used
541       as a prefix to some other template code. Second, because it cannot be
542       used in "pack" at all, and third, in "unpack", doesn't return the data
543       as defined by the template code it precedes. Instead it'll give you an
544       integer of number bits that is computed from the data value by doing
545       sums. For numeric unpack codes, no big feat is achieved:
546
547           my $buf = pack( 'iii', 100, 20, 3 );
548           print unpack( '%32i3', $buf ), "\n";  # prints 123
549
550       For string values, "%" returns the sum of the byte values saving you
551       the trouble of a sum loop with "substr" and "ord":
552
553           print unpack( '%32A*', "\x01\x10" ), "\n";  # prints 17
554
555       Although the "%" code is documented as returning a "checksum": don't
556       put your trust in such values! Even when applied to a small number of
557       bytes, they won't guarantee a noticeable Hamming distance.
558
559       In connection with "b" or "B", "%" simply adds bits, and this can be
560       put to good use to count set bits efficiently:
561
562           my $bitcount = unpack( '%32b*', $mask );
563
564       And an even parity bit can be determined like this:
565
566           my $evenparity = unpack( '%1b*', $mask );
567
568   Unicode
569       Unicode is a character set that can represent most characters in most
570       of the world's languages, providing room for over one million different
571       characters. Unicode 3.1 specifies 94,140 characters: The Basic Latin
572       characters are assigned to the numbers 0 - 127. The Latin-1 Supplement
573       with characters that are used in several European languages is in the
574       next range, up to 255. After some more Latin extensions we find the
575       character sets from languages using non-Roman alphabets, interspersed
576       with a variety of symbol sets such as currency symbols, Zapf Dingbats
577       or Braille.  (You might want to visit <http://www.unicode.org/> for a
578       look at some of them - my personal favourites are Telugu and Kannada.)
579
580       The Unicode character sets associates characters with integers.
581       Encoding these numbers in an equal number of bytes would more than
582       double the requirements for storing texts written in Latin alphabets.
583       The UTF-8 encoding avoids this by storing the most common (from a
584       western point of view) characters in a single byte while encoding the
585       rarer ones in three or more bytes.
586
587       Perl uses UTF-8, internally, for most Unicode strings.
588
589       So what has this got to do with "pack"? Well, if you want to compose a
590       Unicode string (that is internally encoded as UTF-8), you can do so by
591       using template code "U". As an example, let's produce the Euro currency
592       symbol (code number 0x20AC):
593
594          $UTF8{Euro} = pack( 'U', 0x20AC );
595          # Equivalent to: $UTF8{Euro} = "\x{20ac}";
596
597       Inspecting $UTF8{Euro} shows that it contains 3 bytes: "\xe2\x82\xac".
598       However, it contains only 1 character, number 0x20AC.  The round trip
599       can be completed with "unpack":
600
601          $Unicode{Euro} = unpack( 'U', $UTF8{Euro} );
602
603       Unpacking using the "U" template code also works on UTF-8 encoded byte
604       strings.
605
606       Usually you'll want to pack or unpack UTF-8 strings:
607
608          # pack and unpack the Hebrew alphabet
609          my $alefbet = pack( 'U*', 0x05d0..0x05ea );
610          my @hebrew = unpack( 'U*', $utf );
611
612       Please note: in the general case, you're better off using
613       Encode::decode_utf8 to decode a UTF-8 encoded byte string to a Perl
614       Unicode string, and Encode::encode_utf8 to encode a Perl Unicode string
615       to UTF-8 bytes. These functions provide means of handling invalid byte
616       sequences and generally have a friendlier interface.
617
618   Another Portable Binary Encoding
619       The pack code "w" has been added to support a portable binary data
620       encoding scheme that goes way beyond simple integers. (Details can be
621       found at <http://Casbah.org/>, the Scarab project.)  A BER (Binary
622       Encoded Representation) compressed unsigned integer stores base 128
623       digits, most significant digit first, with as few digits as possible.
624       Bit eight (the high bit) is set on each byte except the last. There is
625       no size limit to BER encoding, but Perl won't go to extremes.
626
627          my $berbuf = pack( 'w*', 1, 128, 128+1, 128*128+127 );
628
629       A hex dump of $berbuf, with spaces inserted at the right places, shows
630       01 8100 8101 81807F. Since the last byte is always less than 128,
631       "unpack" knows where to stop.
632

Template Grouping

634       Prior to Perl 5.8, repetitions of templates had to be made by
635       "x"-multiplication of template strings. Now there is a better way as we
636       may use the pack codes "(" and ")" combined with a repeat count.  The
637       "unpack" template from the Stack Frame example can simply be written
638       like this:
639
640          unpack( 'v2 (vXXCC)5 v5', $frame )
641
642       Let's explore this feature a little more. We'll begin with the
643       equivalent of
644
645          join( '', map( substr( $_, 0, 1 ), @str ) )
646
647       which returns a string consisting of the first character from each
648       string.  Using pack, we can write
649
650          pack( '(A)'.@str, @str )
651
652       or, because a repeat count "*" means "repeat as often as required",
653       simply
654
655          pack( '(A)*', @str )
656
657       (Note that the template "A*" would only have packed $str[0] in full
658       length.)
659
660       To pack dates stored as triplets ( day, month, year ) in an array
661       @dates into a sequence of byte, byte, short integer we can write
662
663          $pd = pack( '(CCS)*', map( @$_, @dates ) );
664
665       To swap pairs of characters in a string (with even length) one could
666       use several techniques. First, let's use "x" and "X" to skip forward
667       and back:
668
669          $s = pack( '(A)*', unpack( '(xAXXAx)*', $s ) );
670
671       We can also use "@" to jump to an offset, with 0 being the position
672       where we were when the last "(" was encountered:
673
674          $s = pack( '(A)*', unpack( '(@1A @0A @2)*', $s ) );
675
676       Finally, there is also an entirely different approach by unpacking big
677       endian shorts and packing them in the reverse byte order:
678
679          $s = pack( '(v)*', unpack( '(n)*', $s );
680

Lengths and Widths

682   String Lengths
683       In the previous section we've seen a network message that was
684       constructed by prefixing the binary message length to the actual
685       message. You'll find that packing a length followed by so many bytes of
686       data is a frequently used recipe since appending a null byte won't work
687       if a null byte may be part of the data. Here is an example where both
688       techniques are used: after two null terminated strings with source and
689       destination address, a Short Message (to a mobile phone) is sent after
690       a length byte:
691
692          my $msg = pack( 'Z*Z*CA*', $src, $dst, length( $sm ), $sm );
693
694       Unpacking this message can be done with the same template:
695
696          ( $src, $dst, $len, $sm ) = unpack( 'Z*Z*CA*', $msg );
697
698       There's a subtle trap lurking in the offing: Adding another field after
699       the Short Message (in variable $sm) is all right when packing, but this
700       cannot be unpacked naively:
701
702          # pack a message
703          my $msg = pack( 'Z*Z*CA*C', $src, $dst, length( $sm ), $sm, $prio );
704
705          # unpack fails - $prio remains undefined!
706          ( $src, $dst, $len, $sm, $prio ) = unpack( 'Z*Z*CA*C', $msg );
707
708       The pack code "A*" gobbles up all remaining bytes, and $prio remains
709       undefined! Before we let disappointment dampen the morale: Perl's got
710       the trump card to make this trick too, just a little further up the
711       sleeve.  Watch this:
712
713          # pack a message: ASCIIZ, ASCIIZ, length/string, byte
714          my $msg = pack( 'Z* Z* C/A* C', $src, $dst, $sm, $prio );
715
716          # unpack
717          ( $src, $dst, $sm, $prio ) = unpack( 'Z* Z* C/A* C', $msg );
718
719       Combining two pack codes with a slash ("/") associates them with a
720       single value from the argument list. In "pack", the length of the
721       argument is taken and packed according to the first code while the
722       argument itself is added after being converted with the template code
723       after the slash.  This saves us the trouble of inserting the "length"
724       call, but it is in "unpack" where we really score: The value of the
725       length byte marks the end of the string to be taken from the buffer.
726       Since this combination doesn't make sense except when the second pack
727       code isn't "a*", "A*" or "Z*", Perl won't let you.
728
729       The pack code preceding "/" may be anything that's fit to represent a
730       number: All the numeric binary pack codes, and even text codes such as
731       "A4" or "Z*":
732
733          # pack/unpack a string preceded by its length in ASCII
734          my $buf = pack( 'A4/A*', "Humpty-Dumpty" );
735          # unpack $buf: '13  Humpty-Dumpty'
736          my $txt = unpack( 'A4/A*', $buf );
737
738       "/" is not implemented in Perls before 5.6, so if your code is required
739       to work on older Perls you'll need to "unpack( 'Z* Z* C')" to get the
740       length, then use it to make a new unpack string. For example
741
742          # pack a message: ASCIIZ, ASCIIZ, length, string, byte (5.005 compatible)
743          my $msg = pack( 'Z* Z* C A* C', $src, $dst, length $sm, $sm, $prio );
744
745          # unpack
746          ( undef, undef, $len) = unpack( 'Z* Z* C', $msg );
747          ($src, $dst, $sm, $prio) = unpack ( "Z* Z* x A$len C", $msg );
748
749       But that second "unpack" is rushing ahead. It isn't using a simple
750       literal string for the template. So maybe we should introduce...
751
752   Dynamic Templates
753       So far, we've seen literals used as templates. If the list of pack
754       items doesn't have fixed length, an expression constructing the
755       template is required (whenever, for some reason, "()*" cannot be used).
756       Here's an example: To store named string values in a way that can be
757       conveniently parsed by a C program, we create a sequence of names and
758       null terminated ASCII strings, with "=" between the name and the value,
759       followed by an additional delimiting null byte. Here's how:
760
761          my $env = pack( '(A*A*Z*)' . keys( %Env ) . 'C',
762                          map( { ( $_, '=', $Env{$_} ) } keys( %Env ) ), 0 );
763
764       Let's examine the cogs of this byte mill, one by one. There's the "map"
765       call, creating the items we intend to stuff into the $env buffer: to
766       each key (in $_) it adds the "=" separator and the hash entry value.
767       Each triplet is packed with the template code sequence "A*A*Z*" that is
768       repeated according to the number of keys. (Yes, that's what the "keys"
769       function returns in scalar context.) To get the very last null byte, we
770       add a 0 at the end of the "pack" list, to be packed with "C".
771       (Attentive readers may have noticed that we could have omitted the 0.)
772
773       For the reverse operation, we'll have to determine the number of items
774       in the buffer before we can let "unpack" rip it apart:
775
776          my $n = $env =~ tr/\0// - 1;
777          my %env = map( split( /=/, $_ ), unpack( "(Z*)$n", $env ) );
778
779       The "tr" counts the null bytes. The "unpack" call returns a list of
780       name-value pairs each of which is taken apart in the "map" block.
781
782   Counting Repetitions
783       Rather than storing a sentinel at the end of a data item (or a list of
784       items), we could precede the data with a count. Again, we pack keys and
785       values of a hash, preceding each with an unsigned short length count,
786       and up front we store the number of pairs:
787
788          my $env = pack( 'S(S/A* S/A*)*', scalar keys( %Env ), %Env );
789
790       This simplifies the reverse operation as the number of repetitions can
791       be unpacked with the "/" code:
792
793          my %env = unpack( 'S/(S/A* S/A*)', $env );
794
795       Note that this is one of the rare cases where you cannot use the same
796       template for "pack" and "unpack" because "pack" can't determine a
797       repeat count for a "()"-group.
798
799   Intel HEX
800       Intel HEX is a file format for representing binary data, mostly for
801       programming various chips, as a text file. (See
802       <http://en.wikipedia.org/wiki/.hex> for a detailed description, and
803       <http://en.wikipedia.org/wiki/SREC_(file_format)> for the Motorola
804       S-record format, which can be unravelled using the same technique.)
805       Each line begins with a colon (':') and is followed by a sequence of
806       hexadecimal characters, specifying a byte count n (8 bit), an address
807       (16 bit, big endian), a record type (8 bit), n data bytes and a
808       checksum (8 bit) computed as the least significant byte of the two's
809       complement sum of the preceding bytes. Example: ":0300300002337A1E".
810
811       The first step of processing such a line is the conversion, to binary,
812       of the hexadecimal data, to obtain the four fields, while checking the
813       checksum. No surprise here: we'll start with a simple "pack" call to
814       convert everything to binary:
815
816          my $binrec = pack( 'H*', substr( $hexrec, 1 ) );
817
818       The resulting byte sequence is most convenient for checking the
819       checksum.  Don't slow your program down with a for loop adding the
820       "ord" values of this string's bytes - the "unpack" code "%" is the
821       thing to use for computing the 8-bit sum of all bytes, which must be
822       equal to zero:
823
824          die unless unpack( "%8C*", $binrec ) == 0;
825
826       Finally, let's get those four fields. By now, you shouldn't have any
827       problems with the first three fields - but how can we use the byte
828       count of the data in the first field as a length for the data field?
829       Here the codes "x" and "X" come to the rescue, as they permit jumping
830       back and forth in the string to unpack.
831
832          my( $addr, $type, $data ) = unpack( "x n C X4 C x3 /a", $bin );
833
834       Code "x" skips a byte, since we don't need the count yet. Code "n"
835       takes care of the 16-bit big-endian integer address, and "C" unpacks
836       the record type. Being at offset 4, where the data begins, we need the
837       count.  "X4" brings us back to square one, which is the byte at offset
838       0.  Now we pick up the count, and zoom forth to offset 4, where we are
839       now fully furnished to extract the exact number of data bytes, leaving
840       the trailing checksum byte alone.
841

Packing and Unpacking C Structures

843       In previous sections we have seen how to pack numbers and character
844       strings. If it were not for a couple of snags we could conclude this
845       section right away with the terse remark that C structures don't
846       contain anything else, and therefore you already know all there is to
847       it.  Sorry, no: read on, please.
848
849       If you have to deal with a lot of C structures, and don't want to hack
850       all your template strings manually, you'll probably want to have a look
851       at the CPAN module "Convert::Binary::C". Not only can it parse your C
852       source directly, but it also has built-in support for all the odds and
853       ends described further on in this section.
854
855   The Alignment Pit
856       In the consideration of speed against memory requirements the balance
857       has been tilted in favor of faster execution. This has influenced the
858       way C compilers allocate memory for structures: On architectures where
859       a 16-bit or 32-bit operand can be moved faster between places in
860       memory, or to or from a CPU register, if it is aligned at an even or
861       multiple-of-four or even at a multiple-of eight address, a C compiler
862       will give you this speed benefit by stuffing extra bytes into
863       structures.  If you don't cross the C shoreline this is not likely to
864       cause you any grief (although you should care when you design large
865       data structures, or you want your code to be portable between
866       architectures (you do want that, don't you?)).
867
868       To see how this affects "pack" and "unpack", we'll compare these two C
869       structures:
870
871          typedef struct {
872            char     c1;
873            short    s;
874            char     c2;
875            long     l;
876          } gappy_t;
877
878          typedef struct {
879            long     l;
880            short    s;
881            char     c1;
882            char     c2;
883          } dense_t;
884
885       Typically, a C compiler allocates 12 bytes to a "gappy_t" variable, but
886       requires only 8 bytes for a "dense_t". After investigating this
887       further, we can draw memory maps, showing where the extra 4 bytes are
888       hidden:
889
890          0           +4          +8          +12
891          +--+--+--+--+--+--+--+--+--+--+--+--+
892          |c1|xx|  s  |c2|xx|xx|xx|     l     |    xx = fill byte
893          +--+--+--+--+--+--+--+--+--+--+--+--+
894          gappy_t
895
896          0           +4          +8
897          +--+--+--+--+--+--+--+--+
898          |     l     |  h  |c1|c2|
899          +--+--+--+--+--+--+--+--+
900          dense_t
901
902       And that's where the first quirk strikes: "pack" and "unpack" templates
903       have to be stuffed with "x" codes to get those extra fill bytes.
904
905       The natural question: "Why can't Perl compensate for the gaps?"
906       warrants an answer. One good reason is that C compilers might provide
907       (non-ANSI) extensions permitting all sorts of fancy control over the
908       way structures are aligned, even at the level of an individual
909       structure field. And, if this were not enough, there is an insidious
910       thing called "union" where the amount of fill bytes cannot be derived
911       from the alignment of the next item alone.
912
913       OK, so let's bite the bullet. Here's one way to get the alignment right
914       by inserting template codes "x", which don't take a corresponding item
915       from the list:
916
917         my $gappy = pack( 'cxs cxxx l!', $c1, $s, $c2, $l );
918
919       Note the "!" after "l": We want to make sure that we pack a long
920       integer as it is compiled by our C compiler. And even now, it will only
921       work for the platforms where the compiler aligns things as above.  And
922       somebody somewhere has a platform where it doesn't.  [Probably a Cray,
923       where "short"s, "int"s and "long"s are all 8 bytes. :-)]
924
925       Counting bytes and watching alignments in lengthy structures is bound
926       to be a drag. Isn't there a way we can create the template with a
927       simple program? Here's a C program that does the trick:
928
929          #include <stdio.h>
930          #include <stddef.h>
931
932          typedef struct {
933            char     fc1;
934            short    fs;
935            char     fc2;
936            long     fl;
937          } gappy_t;
938
939          #define Pt(struct,field,tchar) \
940            printf( "@%d%s ", offsetof(struct,field), # tchar );
941
942          int main() {
943            Pt( gappy_t, fc1, c  );
944            Pt( gappy_t, fs,  s! );
945            Pt( gappy_t, fc2, c  );
946            Pt( gappy_t, fl,  l! );
947            printf( "\n" );
948          }
949
950       The output line can be used as a template in a "pack" or "unpack" call:
951
952         my $gappy = pack( '@0c @2s! @4c @8l!', $c1, $s, $c2, $l );
953
954       Gee, yet another template code - as if we hadn't plenty. But "@" saves
955       our day by enabling us to specify the offset from the beginning of the
956       pack buffer to the next item: This is just the value the "offsetof"
957       macro (defined in "<stddef.h>") returns when given a "struct" type and
958       one of its field names ("member-designator" in C standardese).
959
960       Neither using offsets nor adding "x"'s to bridge the gaps is
961       satisfactory.  (Just imagine what happens if the structure changes.)
962       What we really need is a way of saying "skip as many bytes as required
963       to the next multiple of N".  In fluent Templatese, you say this with
964       "x!N" where N is replaced by the appropriate value. Here's the next
965       version of our struct packaging:
966
967         my $gappy = pack( 'c x!2 s c x!4 l!', $c1, $s, $c2, $l );
968
969       That's certainly better, but we still have to know how long all the
970       integers are, and portability is far away. Rather than 2, for instance,
971       we want to say "however long a short is". But this can be done by
972       enclosing the appropriate pack code in brackets: "[s]". So, here's the
973       very best we can do:
974
975         my $gappy = pack( 'c x![s] s c x![l!] l!', $c1, $s, $c2, $l );
976
977   Dealing with Endian-ness
978       Now, imagine that we want to pack the data for a machine with a
979       different byte-order. First, we'll have to figure out how big the data
980       types on the target machine really are. Let's assume that the longs are
981       32 bits wide and the shorts are 16 bits wide. You can then rewrite the
982       template as:
983
984         my $gappy = pack( 'c x![s] s c x![l] l', $c1, $s, $c2, $l );
985
986       If the target machine is little-endian, we could write:
987
988         my $gappy = pack( 'c x![s] s< c x![l] l<', $c1, $s, $c2, $l );
989
990       This forces the short and the long members to be little-endian, and is
991       just fine if you don't have too many struct members. But we could also
992       use the byte-order modifier on a group and write the following:
993
994         my $gappy = pack( '( c x![s] s c x![l] l )<', $c1, $s, $c2, $l );
995
996       This is not as short as before, but it makes it more obvious that we
997       intend to have little-endian byte-order for a whole group, not only for
998       individual template codes. It can also be more readable and easier to
999       maintain.
1000
1001   Alignment, Take 2
1002       I'm afraid that we're not quite through with the alignment catch yet.
1003       The hydra raises another ugly head when you pack arrays of structures:
1004
1005          typedef struct {
1006            short    count;
1007            char     glyph;
1008          } cell_t;
1009
1010          typedef cell_t buffer_t[BUFLEN];
1011
1012       Where's the catch? Padding is neither required before the first field
1013       "count", nor between this and the next field "glyph", so why can't we
1014       simply pack like this:
1015
1016          # something goes wrong here:
1017          pack( 's!a' x @buffer,
1018                map{ ( $_->{count}, $_->{glyph} ) } @buffer );
1019
1020       This packs "3*@buffer" bytes, but it turns out that the size of
1021       "buffer_t" is four times "BUFLEN"! The moral of the story is that the
1022       required alignment of a structure or array is propagated to the next
1023       higher level where we have to consider padding at the end of each
1024       component as well. Thus the correct template is:
1025
1026          pack( 's!ax' x @buffer,
1027                map{ ( $_->{count}, $_->{glyph} ) } @buffer );
1028
1029   Alignment, Take 3
1030       And even if you take all the above into account, ANSI still lets this:
1031
1032          typedef struct {
1033            char     foo[2];
1034          } foo_t;
1035
1036       vary in size. The alignment constraint of the structure can be greater
1037       than any of its elements. [And if you think that this doesn't affect
1038       anything common, dismember the next cellphone that you see. Many have
1039       ARM cores, and the ARM structure rules make "sizeof (foo_t)" == 4]
1040
1041   Pointers for How to Use Them
1042       The title of this section indicates the second problem you may run into
1043       sooner or later when you pack C structures. If the function you intend
1044       to call expects a, say, "void *" value, you cannot simply take a
1045       reference to a Perl variable. (Although that value certainly is a
1046       memory address, it's not the address where the variable's contents are
1047       stored.)
1048
1049       Template code "P" promises to pack a "pointer to a fixed length
1050       string".  Isn't this what we want? Let's try:
1051
1052           # allocate some storage and pack a pointer to it
1053           my $memory = "\x00" x $size;
1054           my $memptr = pack( 'P', $memory );
1055
1056       But wait: doesn't "pack" just return a sequence of bytes? How can we
1057       pass this string of bytes to some C code expecting a pointer which is,
1058       after all, nothing but a number? The answer is simple: We have to
1059       obtain the numeric address from the bytes returned by "pack".
1060
1061           my $ptr = unpack( 'L!', $memptr );
1062
1063       Obviously this assumes that it is possible to typecast a pointer to an
1064       unsigned long and vice versa, which frequently works but should not be
1065       taken as a universal law. - Now that we have this pointer the next
1066       question is: How can we put it to good use? We need a call to some C
1067       function where a pointer is expected. The read(2) system call comes to
1068       mind:
1069
1070           ssize_t read(int fd, void *buf, size_t count);
1071
1072       After reading perlfunc explaining how to use "syscall" we can write
1073       this Perl function copying a file to standard output:
1074
1075           require 'syscall.ph';
1076           sub cat($){
1077               my $path = shift();
1078               my $size = -s $path;
1079               my $memory = "\x00" x $size;  # allocate some memory
1080               my $ptr = unpack( 'L', pack( 'P', $memory ) );
1081               open( F, $path ) || die( "$path: cannot open ($!)\n" );
1082               my $fd = fileno(F);
1083               my $res = syscall( &SYS_read, fileno(F), $ptr, $size );
1084               print $memory;
1085               close( F );
1086           }
1087
1088       This is neither a specimen of simplicity nor a paragon of portability
1089       but it illustrates the point: We are able to sneak behind the scenes
1090       and access Perl's otherwise well-guarded memory! (Important note:
1091       Perl's "syscall" does not require you to construct pointers in this
1092       roundabout way. You simply pass a string variable, and Perl forwards
1093       the address.)
1094
1095       How does "unpack" with "P" work? Imagine some pointer in the buffer
1096       about to be unpacked: If it isn't the null pointer (which will smartly
1097       produce the "undef" value) we have a start address - but then what?
1098       Perl has no way of knowing how long this "fixed length string" is, so
1099       it's up to you to specify the actual size as an explicit length after
1100       "P".
1101
1102          my $mem = "abcdefghijklmn";
1103          print unpack( 'P5', pack( 'P', $mem ) ); # prints "abcde"
1104
1105       As a consequence, "pack" ignores any number or "*" after "P".
1106
1107       Now that we have seen "P" at work, we might as well give "p" a whirl.
1108       Why do we need a second template code for packing pointers at all? The
1109       answer lies behind the simple fact that an "unpack" with "p" promises a
1110       null-terminated string starting at the address taken from the buffer,
1111       and that implies a length for the data item to be returned:
1112
1113          my $buf = pack( 'p', "abc\x00efhijklmn" );
1114          print unpack( 'p', $buf );    # prints "abc"
1115
1116       Albeit this is apt to be confusing: As a consequence of the length
1117       being implied by the string's length, a number after pack code "p" is a
1118       repeat count, not a length as after "P".
1119
1120       Using "pack(..., $x)" with "P" or "p" to get the address where $x is
1121       actually stored must be used with circumspection. Perl's internal
1122       machinery considers the relation between a variable and that address as
1123       its very own private matter and doesn't really care that we have
1124       obtained a copy. Therefore:
1125
1126       ·   Do not use "pack" with "p" or "P" to obtain the address of variable
1127           that's bound to go out of scope (and thereby freeing its memory)
1128           before you are done with using the memory at that address.
1129
1130       ·   Be very careful with Perl operations that change the value of the
1131           variable. Appending something to the variable, for instance, might
1132           require reallocation of its storage, leaving you with a pointer
1133           into no-man's land.
1134
1135       ·   Don't think that you can get the address of a Perl variable when it
1136           is stored as an integer or double number! "pack('P', $x)" will
1137           force the variable's internal representation to string, just as if
1138           you had written something like "$x .= ''".
1139
1140       It's safe, however, to P- or p-pack a string literal, because Perl
1141       simply allocates an anonymous variable.
1142

Pack Recipes

1144       Here are a collection of (possibly) useful canned recipes for "pack"
1145       and "unpack":
1146
1147           # Convert IP address for socket functions
1148           pack( "C4", split /\./, "123.4.5.6" );
1149
1150           # Count the bits in a chunk of memory (e.g. a select vector)
1151           unpack( '%32b*', $mask );
1152
1153           # Determine the endianness of your system
1154           $is_little_endian = unpack( 'c', pack( 's', 1 ) );
1155           $is_big_endian = unpack( 'xc', pack( 's', 1 ) );
1156
1157           # Determine the number of bits in a native integer
1158           $bits = unpack( '%32I!', ~0 );
1159
1160           # Prepare argument for the nanosleep system call
1161           my $timespec = pack( 'L!L!', $secs, $nanosecs );
1162
1163       For a simple memory dump we unpack some bytes into just as many pairs
1164       of hex digits, and use "map" to handle the traditional spacing - 16
1165       bytes to a line:
1166
1167           my $i;
1168           print map( ++$i % 16 ? "$_ " : "$_\n",
1169                      unpack( 'H2' x length( $mem ), $mem ) ),
1170                 length( $mem ) % 16 ? "\n" : '';
1171

Funnies Section

1173           # Pulling digits out of nowhere...
1174           print unpack( 'C', pack( 'x' ) ),
1175                 unpack( '%B*', pack( 'A' ) ),
1176                 unpack( 'H', pack( 'A' ) ),
1177                 unpack( 'A', unpack( 'C', pack( 'A' ) ) ), "\n";
1178
1179           # One for the road ;-)
1180           my $advice = pack( 'all u can in a van' );
1181

Authors

1183       Simon Cozens and Wolfgang Laun.
1184
1185
1186
1187perl v5.12.4                      2011-06-01                    PERLPACKTUT(1)
Impressum