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, 30..39 );
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 Zed'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) =
174               unpack("A10xA27xA7xA*", $_);
175
176       Now, that's our data parsed. I suppose what we might want to do now is
177       total up our income and expenditure, and add another line to the end of
178       our ledger - in the same format - saying how much we've brought in and
179       how much we've spent:
180
181           while (<>) {
182               my ($date, $desc, $income, $expend) =
183                   unpack("A10xA27xA7xA*", $_);
184               $tot_income += $income;
185               $tot_expend += $expend;
186           }
187
188           $tot_income = sprintf("%.2f", $tot_income); # Get them into
189           $tot_expend = sprintf("%.2f", $tot_expend); # "financial" format
190
191           $date = POSIX::strftime("%m/%d/%Y", localtime);
192
193           # OK, let's go:
194
195           print pack("A10xA27xA7xA*", $date, "Totals",
196               $tot_income, $tot_expend);
197
198       Oh, hmm. That didn't quite work. Let's see what happened:
199
200           01/24/2001 Zed's Camel Emporium                     1147.99
201           01/28/2001 Flea spray                                 24.99
202           01/29/2001 Camel rides to tourists     1235.00
203           03/23/2001Totals                     1235.001172.98
204
205       OK, it's a start, but what happened to the spaces? We put "x", didn't
206       we? Shouldn't it skip forward? Let's look at what "pack" in perlfunc
207       says:
208
209           x   A null byte.
210
211       Urgh. No wonder. There's a big difference between "a null byte",
212       character zero, and "a space", character 32. Perl's put something
213       between the date and the description - but unfortunately, we can't see
214       it!
215
216       What we actually need to do is expand the width of the fields. The "A"
217       format pads any non-existent characters with spaces, so we can use the
218       additional spaces to line up our fields, like this:
219
220           print pack("A11 A28 A8 A*", $date, "Totals",
221               $tot_income, $tot_expend);
222
223       (Note that you can put spaces in the template to make it more readable,
224       but they don't translate to spaces in the output.) Here's what we got
225       this time:
226
227           01/24/2001 Zed's Camel Emporium                     1147.99
228           01/28/2001 Flea spray                                 24.99
229           01/29/2001 Camel rides to tourists     1235.00
230           03/23/2001 Totals                      1235.00 1172.98
231
232       That's a bit better, but we still have that last column which needs to
233       be moved further over. There's an easy way to fix this up:
234       unfortunately, we can't get "pack" to right-justify our fields, but we
235       can get "sprintf" to do it:
236
237           $tot_income = sprintf("%.2f", $tot_income);
238           $tot_expend = sprintf("%12.2f", $tot_expend);
239           $date = POSIX::strftime("%m/%d/%Y", localtime);
240           print pack("A11 A28 A8 A*", $date, "Totals",
241               $tot_income, $tot_expend);
242
243       This time we get the right answer:
244
245           01/28/2001 Flea spray                                 24.99
246           01/29/2001 Camel rides to tourists     1235.00
247           03/23/2001 Totals                      1235.00      1172.98
248
249       So that's how we consume and produce fixed-width data. Let's recap what
250       we've seen of "pack" and "unpack" so far:
251
252       ·  Use "pack" to go from several pieces of data to one fixed-width
253          version; use "unpack" to turn a fixed-width-format string into
254          several pieces of data.
255
256       ·  The pack format "A" means "any character"; if you're "pack"ing and
257          you've run out of things to pack, "pack" will fill the rest up with
258          spaces.
259
260       ·  "x" means "skip a byte" when "unpack"ing; when "pack"ing, it means
261          "introduce a null byte" - that's probably not what you mean if
262          you're dealing with plain text.
263
264       ·  You can follow the formats with numbers to say how many characters
265          should be affected by that format: "A12" means "take 12 characters";
266          "x6" means "skip 6 bytes" or "character 0, 6 times".
267
268       ·  Instead of a number, you can use "*" to mean "consume everything
269          else left".
270
271          Warning: when packing multiple pieces of data, "*" only means
272          "consume all of the current piece of data". That's to say
273
274              pack("A*A*", $one, $two)
275
276          packs all of $one into the first "A*" and then all of $two into the
277          second. This is a general principle: each format character
278          corresponds to one piece of data to be "pack"ed.
279

Packing Numbers

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

Exotic Templates

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

Template Grouping

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

Lengths and Widths

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

Packing and Unpacking C Structures

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

Pack Recipes

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

Funnies Section

1184           # Pulling digits out of nowhere...
1185           print unpack( 'C', pack( 'x' ) ),
1186                 unpack( '%B*', pack( 'A' ) ),
1187                 unpack( 'H', pack( 'A' ) ),
1188                 unpack( 'A', unpack( 'C', pack( 'A' ) ) ), "\n";
1189
1190           # One for the road ;-)
1191           my $advice = pack( 'all u can in a van' );
1192

Authors

1194       Simon Cozens and Wolfgang Laun.
1195
1196
1197
1198perl v5.30.1                      2019-11-29                    PERLPACKTUT(1)
Impressum