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, $cx, $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 <https://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
632       <https://github.com/mworks-project/mw_scarab/blob/master/Scarab-0.1.00d19/doc/binary-serialization.txt>,
633       the Scarab project.)  A BER (Binary Encoded Representation) compressed
634       unsigned integer stores base 128 digits, most significant digit first,
635       with as few digits as possible.  Bit eight (the high bit) is set on
636       each byte except the last. There is no size limit to BER encoding, but
637       Perl won't go to extremes.
638
639          my $berbuf = pack( 'w*', 1, 128, 128+1, 128*128+127 );
640
641       A hex dump of $berbuf, with spaces inserted at the right places, shows
642       01 8100 8101 81807F. Since the last byte is always less than 128,
643       "unpack" knows where to stop.
644

Template Grouping

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

Lengths and Widths

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

Packing and Unpacking C Structures

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

Pack Recipes

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

Funnies Section

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

Authors

1196       Simon Cozens and Wolfgang Laun.
1197
1198
1199
1200perl v5.36.0                      2022-08-30                    PERLPACKTUT(1)
Impressum