Debian Codegraph @

upstream/fedora-44/man1/perlpacktut.1

raw
1 .\" -*- mode: troff; coding: utf-8 -*-
2 .\" Automatically generated by Pod::Man v6.0.2 (Pod::Simple 3.45)
3 .\"
4 .\" Standard preamble:
5 .\" ========================================================================
6 .de Sp \" Vertical space (when we can't use .PP)
7 .if t .sp .5v
8 .if n .sp
9 ..
10 .de Vb \" Begin verbatim text
11 .ft CW
12 .nf
13 .ne \\$1
14 ..
15 .de Ve \" End verbatim text
16 .ft R
17 .fi
18 ..
19 .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>.
20 .ie n \{\
21 . ds C` ""
22 . ds C' ""
23 'br\}
24 .el\{\
25 . ds C`
26 . ds C'
27 'br\}
28 .\"
29 .\" Escape single quotes in literal strings from groff's Unicode transform.
30 .ie \n(.g .ds Aq \(aq
31 .el .ds Aq '
32 .\"
33 .\" If the F register is >0, we'll generate index entries on stderr for
34 .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
35 .\" entries marked with X<> in POD. Of course, you'll have to process the
36 .\" output yourself in some meaningful fashion.
37 .\"
38 .\" Avoid warning from groff about undefined register 'F'.
39 .de IX
40 ..
41 .nr rF 0
42 .if \n(.g .if rF .nr rF 1
43 .if (\n(rF:(\n(.g==0)) \{\
44 . if \nF \{\
45 . de IX
46 . tm Index:\\$1\t\\n%\t"\\$2"
47 ..
48 . if !\nF==2 \{\
49 . nr % 0
50 . nr F 2
51 . \}
52 . \}
53 .\}
54 .rr rF
55 .\"
56 .\" Required to disable full justification in groff 1.23.0.
57 .if n .ds AD l
58 .\" ========================================================================
59 .\"
60 .IX Title "PERLPACKTUT 1"
61 .TH PERLPACKTUT 1 2026-03-09 "perl v5.42.1" "Perl Programmers Reference Guide"
62 .\" For nroff, turn off justification. Always turn off hyphenation; it makes
63 .\" way too many mistakes in technical documents.
64 .if n .ad l
65 .nh
66 .SH NAME
67 perlpacktut \- tutorial on "pack" and "unpack"
68 .SH DESCRIPTION
69 .IX Header "DESCRIPTION"
70 \&\f(CW\*(C`pack\*(C'\fR and \f(CW\*(C`unpack\*(C'\fR are two functions for transforming data according
71 to a user\-defined template, between the guarded way Perl stores values
72 and some well\-defined representation as might be required in the
73 environment of a Perl program. Unfortunately, they\*(Aqre also two of
74 the most misunderstood and most often overlooked functions that Perl
75 provides. This tutorial will demystify them for you.
76 .SH "The Basic Principle"
77 .IX Header "The Basic Principle"
78 Most programming languages don\*(Aqt shelter the memory where variables are
79 stored. In C, for instance, you can take the address of some variable,
80 and the \f(CW\*(C`sizeof\*(C'\fR operator tells you how many bytes are allocated to
81 the variable. Using the address and the size, you may access the storage
82 to your heart\*(Aqs content.
83 .PP
84 In Perl, you just can\*(Aqt access memory at random, but the structural and
85 representational conversion provided by \f(CW\*(C`pack\*(C'\fR and \f(CW\*(C`unpack\*(C'\fR is an
86 excellent alternative. The \f(CW\*(C`pack\*(C'\fR function converts values to a byte
87 sequence containing representations according to a given specification,
88 the so\-called "template" argument. \f(CW\*(C`unpack\*(C'\fR is the reverse process,
89 deriving some values from the contents of a string of bytes. (Be cautioned,
90 however, that not all that has been packed together can be neatly unpacked \-
91 a very common experience as seasoned travellers are likely to confirm.)
92 .PP
93 Why, you may ask, would you need a chunk of memory containing some values
94 in binary representation? One good reason is input and output accessing
95 some file, a device, or a network connection, whereby this binary
96 representation is either forced on you or will give you some benefit
97 in processing. Another cause is passing data to some system call that
98 is not available as a Perl function: \f(CW\*(C`syscall\*(C'\fR requires you to provide
99 parameters stored in the way it happens in a C program. Even text processing
100 (as shown in the next section) may be simplified with judicious usage
101 of these two functions.
102 .PP
103 To see how (un)packing works, we\*(Aqll start with a simple template
104 code where the conversion is in low gear: between the contents of a byte
105 sequence and a string of hexadecimal digits. Let\*(Aqs use \f(CW\*(C`unpack\*(C'\fR, since
106 this is likely to remind you of a dump program, or some desperate last
107 message unfortunate programs are wont to throw at you before they expire
108 into the wild blue yonder. Assuming that the variable \f(CW$mem\fR holds a
109 sequence of bytes that we\*(Aqd like to inspect without assuming anything
110 about its meaning, we can write
111 .PP
112 .Vb 2
113 \& my( $hex ) = unpack( \*(AqH*\*(Aq, $mem );
114 \& print "$hex\en";
115 .Ve
116 .PP
117 whereupon we might see something like this, with each pair of hex digits
118 corresponding to a byte:
119 .PP
120 .Vb 1
121 \& 41204d414e204120504c414e20412043414e414c2050414e414d41
122 .Ve
123 .PP
124 What was in this chunk of memory? Numbers, characters, or a mixture of
125 both? Assuming that we\*(Aqre on a computer where ASCII (or some similar)
126 encoding is used: hexadecimal values in the range \f(CW0x40\fR \- \f(CW0x5A\fR
127 indicate an uppercase letter, and \f(CW0x20\fR encodes a space. So we might
128 assume it is a piece of text, which some are able to read like a tabloid;
129 but others will have to get hold of an ASCII table and relive that
130 firstgrader feeling. Not caring too much about which way to read this,
131 we note that \f(CW\*(C`unpack\*(C'\fR with the template code \f(CW\*(C`H\*(C'\fR converts the contents
132 of a sequence of bytes into the customary hexadecimal notation. Since
133 "a sequence of" is a pretty vague indication of quantity, \f(CW\*(C`H\*(C'\fR has been
134 defined to convert just a single hexadecimal digit unless it is followed
135 by a repeat count. An asterisk for the repeat count means to use whatever
136 remains.
137 .PP
138 The inverse operation \- packing byte contents from a string of hexadecimal
139 digits \- is just as easily written. For instance:
140 .PP
141 .Vb 2
142 \& my $s = pack( \*(AqH2\*(Aq x 10, 30..39 );
143 \& print "$s\en";
144 .Ve
145 .PP
146 Since we feed a list of ten 2\-digit hexadecimal strings to \f(CW\*(C`pack\*(C'\fR, the
147 pack template should contain ten pack codes. If this is run on a computer
148 with ASCII character coding, it will print \f(CW0123456789\fR.
149 .SH "Packing Text"
150 .IX Header "Packing Text"
151 Let\*(Aqs suppose you\*(Aqve got to read in a data file like this:
152 .PP
153 .Vb 4
154 \& Date |Description | Income|Expenditure
155 \& 01/24/2001 Zed\*(Aqs Camel Emporium 1147.99
156 \& 01/28/2001 Flea spray 24.99
157 \& 01/29/2001 Camel rides to tourists 235.00
158 .Ve
159 .PP
160 How do we do it? You might think first to use \f(CW\*(C`split\*(C'\fR; however, since
161 \&\f(CW\*(C`split\*(C'\fR collapses blank fields, you\*(Aqll never know whether a record was
162 income or expenditure. Oops. Well, you could always use \f(CW\*(C`substr\*(C'\fR:
163 .PP
164 .Vb 7
165 \& while (<>) {
166 \& my $date = substr($_, 0, 11);
167 \& my $desc = substr($_, 12, 27);
168 \& my $income = substr($_, 40, 7);
169 \& my $expend = substr($_, 52, 7);
170 \& ...
171 \& }
172 .Ve
173 .PP
174 It\*(Aqs not really a barrel of laughs, is it? In fact, it\*(Aqs worse than it
175 may seem; the eagle\-eyed may notice that the first field should only be
176 10 characters wide, and the error has propagated right through the other
177 numbers \- which we\*(Aqve had to count by hand. So it\*(Aqs error\-prone as well
178 as horribly unfriendly.
179 .PP
180 Or maybe we could use regular expressions:
181 .PP
182 .Vb 5
183 \& while (<>) {
184 \& my($date, $desc, $income, $expend) =
185 \& m|(\ed\ed/\ed\ed/\ed{4}) (.{27}) (.{7})(.*)|;
186 \& ...
187 \& }
188 .Ve
189 .PP
190 Urgh. Well, it\*(Aqs a bit better, but \- well, would you want to maintain
191 that?
192 .PP
193 Hey, isn\*(Aqt Perl supposed to make this sort of thing easy? Well, it does,
194 if you use the right tools. \f(CW\*(C`pack\*(C'\fR and \f(CW\*(C`unpack\*(C'\fR are designed to help
195 you out when dealing with fixed\-width data like the above. Let\*(Aqs have a
196 look at a solution with \f(CW\*(C`unpack\*(C'\fR:
197 .PP
198 .Vb 4
199 \& while (<>) {
200 \& my($date, $desc, $income, $expend) = unpack("A10xA27xA7A*", $_);
201 \& ...
202 \& }
203 .Ve
204 .PP
205 That looks a bit nicer; but we\*(Aqve got to take apart that weird template.
206 Where did I pull that out of?
207 .PP
208 OK, let\*(Aqs have a look at some of our data again; in fact, we\*(Aqll include
209 the headers, and a handy ruler so we can keep track of where we are.
210 .PP
211 .Vb 5
212 \& 1 2 3 4 5
213 \& 1234567890123456789012345678901234567890123456789012345678
214 \& Date |Description | Income|Expenditure
215 \& 01/28/2001 Flea spray 24.99
216 \& 01/29/2001 Camel rides to tourists 235.00
217 .Ve
218 .PP
219 From this, we can see that the date column stretches from column 1 to
220 column 10 \- ten characters wide. The \f(CW\*(C`pack\*(C'\fR\-ese for "character" is
221 \&\f(CW\*(C`A\*(C'\fR, and ten of them are \f(CW\*(C`A10\*(C'\fR. So if we just wanted to extract the
222 dates, we could say this:
223 .PP
224 .Vb 1
225 \& my($date) = unpack("A10", $_);
226 .Ve
227 .PP
228 OK, what\*(Aqs next? Between the date and the description is a blank column;
229 we want to skip over that. The \f(CW\*(C`x\*(C'\fR template means "skip forward", so we
230 want one of those. Next, we have another batch of characters, from 12 to
231 38. That\*(Aqs 27 more characters, hence \f(CW\*(C`A27\*(C'\fR. (Don\*(Aqt make the fencepost
232 error \- there are 27 characters between 12 and 38, not 26. Count \*(Aqem!)
233 .PP
234 Now we skip another character and pick up the next 7 characters:
235 .PP
236 .Vb 1
237 \& my($date,$description,$income) = unpack("A10xA27xA7", $_);
238 .Ve
239 .PP
240 Now comes the clever bit. Lines in our ledger which are just income and
241 not expenditure might end at column 46. Hence, we don\*(Aqt want to tell our
242 \&\f(CW\*(C`unpack\*(C'\fR pattern that we \fBneed\fR to find another 12 characters; we\*(Aqll
243 just say "if there\*(Aqs anything left, take it". As you might guess from
244 regular expressions, that\*(Aqs what the \f(CW\*(C`*\*(C'\fR means: "use everything
245 remaining".
246 .IP \(bu 3
247 Be warned, though, that unlike regular expressions, if the \f(CW\*(C`unpack\*(C'\fR
248 template doesn\*(Aqt match the incoming data, Perl will scream and die.
249 .PP
250 Hence, putting it all together:
251 .PP
252 .Vb 2
253 \& my ($date, $description, $income, $expend) =
254 \& unpack("A10xA27xA7xA*", $_);
255 .Ve
256 .PP
257 Now, that\*(Aqs our data parsed. I suppose what we might want to do now is
258 total up our income and expenditure, and add another line to the end of
259 our ledger \- in the same format \- saying how much we\*(Aqve brought in and
260 how much we\*(Aqve spent:
261 .PP
262 .Vb 6
263 \& while (<>) {
264 \& my ($date, $desc, $income, $expend) =
265 \& unpack("A10xA27xA7xA*", $_);
266 \& $tot_income += $income;
267 \& $tot_expend += $expend;
268 \& }
269 \&
270 \& $tot_income = sprintf("%.2f", $tot_income); # Get them into
271 \& $tot_expend = sprintf("%.2f", $tot_expend); # "financial" format
272 \&
273 \& $date = POSIX::strftime("%m/%d/%Y", localtime);
274 \&
275 \& # OK, let\*(Aqs go:
276 \&
277 \& print pack("A10xA27xA7xA*", $date, "Totals",
278 \& $tot_income, $tot_expend);
279 .Ve
280 .PP
281 Oh, hmm. That didn\*(Aqt quite work. Let\*(Aqs see what happened:
282 .PP
283 .Vb 4
284 \& 01/24/2001 Zed\*(Aqs Camel Emporium 1147.99
285 \& 01/28/2001 Flea spray 24.99
286 \& 01/29/2001 Camel rides to tourists 1235.00
287 \& 03/23/2001Totals 1235.001172.98
288 .Ve
289 .PP
290 OK, it\*(Aqs a start, but what happened to the spaces? We put \f(CW\*(C`x\*(C'\fR, didn\*(Aqt
291 we? Shouldn\*(Aqt it skip forward? Let\*(Aqs look at what "pack" in perlfunc says:
292 .PP
293 .Vb 1
294 \& x A null byte.
295 .Ve
296 .PP
297 Urgh. No wonder. There\*(Aqs a big difference between "a null byte",
298 character zero, and "a space", character 32. Perl\*(Aqs put something
299 between the date and the description \- but unfortunately, we can\*(Aqt see
300 it!
301 .PP
302 What we actually need to do is expand the width of the fields. The \f(CW\*(C`A\*(C'\fR
303 format pads any non\-existent characters with spaces, so we can use the
304 additional spaces to line up our fields, like this:
305 .PP
306 .Vb 2
307 \& print pack("A11 A28 A8 A*", $date, "Totals",
308 \& $tot_income, $tot_expend);
309 .Ve
310 .PP
311 (Note that you can put spaces in the template to make it more readable,
312 but they don\*(Aqt translate to spaces in the output.) Here\*(Aqs what we got
313 this time:
314 .PP
315 .Vb 4
316 \& 01/24/2001 Zed\*(Aqs Camel Emporium 1147.99
317 \& 01/28/2001 Flea spray 24.99
318 \& 01/29/2001 Camel rides to tourists 1235.00
319 \& 03/23/2001 Totals 1235.00 1172.98
320 .Ve
321 .PP
322 That\*(Aqs a bit better, but we still have that last column which needs to
323 be moved further over. There\*(Aqs an easy way to fix this up:
324 unfortunately, we can\*(Aqt get \f(CW\*(C`pack\*(C'\fR to right\-justify our fields, but we
325 can get \f(CW\*(C`sprintf\*(C'\fR to do it:
326 .PP
327 .Vb 5
328 \& $tot_income = sprintf("%.2f", $tot_income);
329 \& $tot_expend = sprintf("%12.2f", $tot_expend);
330 \& $date = POSIX::strftime("%m/%d/%Y", localtime);
331 \& print pack("A11 A28 A8 A*", $date, "Totals",
332 \& $tot_income, $tot_expend);
333 .Ve
334 .PP
335 This time we get the right answer:
336 .PP
337 .Vb 3
338 \& 01/28/2001 Flea spray 24.99
339 \& 01/29/2001 Camel rides to tourists 1235.00
340 \& 03/23/2001 Totals 1235.00 1172.98
341 .Ve
342 .PP
343 So that\*(Aqs how we consume and produce fixed\-width data. Let\*(Aqs recap what
344 we\*(Aqve seen of \f(CW\*(C`pack\*(C'\fR and \f(CW\*(C`unpack\*(C'\fR so far:
345 .IP \(bu 3
346 Use \f(CW\*(C`pack\*(C'\fR to go from several pieces of data to one fixed\-width
347 version; use \f(CW\*(C`unpack\*(C'\fR to turn a fixed\-width\-format string into several
348 pieces of data.
349 .IP \(bu 3
350 The pack format \f(CW\*(C`A\*(C'\fR means "any character"; if you\*(Aqre \f(CW\*(C`pack\*(C'\fRing and
351 you\*(Aqve run out of things to pack, \f(CW\*(C`pack\*(C'\fR will fill the rest up with
352 spaces.
353 .IP \(bu 3
354 \&\f(CW\*(C`x\*(C'\fR means "skip a byte" when \f(CW\*(C`unpack\*(C'\fRing; when \f(CW\*(C`pack\*(C'\fRing, it means
355 "introduce a null byte" \- that\*(Aqs probably not what you mean if you\*(Aqre
356 dealing with plain text.
357 .IP \(bu 3
358 You can follow the formats with numbers to say how many characters
359 should be affected by that format: \f(CW\*(C`A12\*(C'\fR means "take 12 characters";
360 \&\f(CW\*(C`x6\*(C'\fR means "skip 6 bytes" or "character 0, 6 times".
361 .IP \(bu 3
362 Instead of a number, you can use \f(CW\*(C`*\*(C'\fR to mean "consume everything else
363 left".
364 .Sp
365 \&\fBWarning\fR: when packing multiple pieces of data, \f(CW\*(C`*\*(C'\fR only means
366 "consume all of the current piece of data". That\*(Aqs to say
367 .Sp
368 .Vb 1
369 \& pack("A*A*", $one, $two)
370 .Ve
371 .Sp
372 packs all of \f(CW$one\fR into the first \f(CW\*(C`A*\*(C'\fR and then all of \f(CW$two\fR into
373 the second. This is a general principle: each format character
374 corresponds to one piece of data to be \f(CW\*(C`pack\*(C'\fRed.
375 .SH "Packing Numbers"
376 .IX Header "Packing Numbers"
377 So much for textual data. Let\*(Aqs get onto the meaty stuff that \f(CW\*(C`pack\*(C'\fR
378 and \f(CW\*(C`unpack\*(C'\fR are best at: handling binary formats for numbers. There is,
379 of course, not just one binary format \- life would be too simple \- but
380 Perl will do all the finicky labor for you.
381 .SS Integers
382 .IX Subsection "Integers"
383 Packing and unpacking numbers implies conversion to and from some
384 \&\fIspecific\fR binary representation. Leaving floating point numbers
385 aside for the moment, the salient properties of any such representation
386 are:
387 .IP \(bu 4
388 the number of bytes used for storing the integer,
389 .IP \(bu 4
390 whether the contents are interpreted as a signed or unsigned number,
391 .IP \(bu 4
392 the byte ordering: whether the first byte is the least or most
393 significant byte (or: little\-endian or big\-endian, respectively).
394 .PP
395 So, for instance, to pack 20302 to a signed 16 bit integer in your
396 computer\*(Aqs representation you write
397 .PP
398 .Vb 1
399 \& my $ps = pack( \*(Aqs\*(Aq, 20302 );
400 .Ve
401 .PP
402 Again, the result is a string, now containing 2 bytes. If you print
403 this string (which is, generally, not recommended) you might see
404 \&\f(CW\*(C`ON\*(C'\fR or \f(CW\*(C`NO\*(C'\fR (depending on your system\*(Aqs byte ordering) \- or something
405 entirely different if your computer doesn\*(Aqt use ASCII character encoding.
406 Unpacking \f(CW$ps\fR with the same template returns the original integer value:
407 .PP
408 .Vb 1
409 \& my( $s ) = unpack( \*(Aqs\*(Aq, $ps );
410 .Ve
411 .PP
412 This is true for all numeric template codes. But don\*(Aqt expect miracles:
413 if the packed value exceeds the allotted byte capacity, high order bits
414 are silently discarded, and unpack certainly won\*(Aqt be able to pull them
415 back out of some magic hat. And, when you pack using a signed template
416 code such as \f(CW\*(C`s\*(C'\fR, an excess value may result in the sign bit
417 getting set, and unpacking this will smartly return a negative value.
418 .PP
419 16 bits won\*(Aqt get you too far with integers, but there is \f(CW\*(C`l\*(C'\fR and \f(CW\*(C`L\*(C'\fR
420 for signed and unsigned 32\-bit integers. And if this is not enough and
421 your system supports 64 bit integers you can push the limits much closer
422 to infinity with pack codes \f(CW\*(C`q\*(C'\fR and \f(CW\*(C`Q\*(C'\fR. A notable exception is provided
423 by pack codes \f(CW\*(C`i\*(C'\fR and \f(CW\*(C`I\*(C'\fR for signed and unsigned integers of the
424 "local custom" variety: Such an integer will take up as many bytes as
425 a local C compiler returns for \f(CWsizeof(int)\fR, but it\*(Aqll use \fIat least\fR
426 32 bits.
427 .PP
428 Each of the integer pack codes \f(CW\*(C`sSlLqQ\*(C'\fR results in a fixed number of bytes,
429 no matter where you execute your program. This may be useful for some
430 applications, but it does not provide for a portable way to pass data
431 structures between Perl and C programs (bound to happen when you call
432 XS extensions or the Perl function \f(CW\*(C`syscall\*(C'\fR), or when you read or
433 write binary files. What you\*(Aqll need in this case are template codes that
434 depend on what your local C compiler compiles when you code \f(CW\*(C`short\*(C'\fR or
435 \&\f(CW\*(C`unsigned long\*(C'\fR, for instance. These codes and their corresponding
436 byte lengths are shown in the table below. Since the C standard leaves
437 much leeway with respect to the relative sizes of these data types, actual
438 values may vary, and that\*(Aqs why the values are given as expressions in
439 C and Perl. (If you\*(Aqd like to use values from \f(CW%Config\fR in your program
440 you have to import it with \f(CW\*(C`use Config\*(C'\fR.)
441 .PP
442 .Vb 5
443 \& signed unsigned byte length in C byte length in Perl
444 \& s! S! sizeof(short) $Config{shortsize}
445 \& i! I! sizeof(int) $Config{intsize}
446 \& l! L! sizeof(long) $Config{longsize}
447 \& q! Q! sizeof(long long) $Config{longlongsize}
448 .Ve
449 .PP
450 The \f(CW\*(C`i!\*(C'\fR and \f(CW\*(C`I!\*(C'\fR codes aren\*(Aqt different from \f(CW\*(C`i\*(C'\fR and \f(CW\*(C`I\*(C'\fR; they are
451 tolerated for completeness\*(Aq sake.
452 .SS "Unpacking a Stack Frame"
453 .IX Subsection "Unpacking a Stack Frame"
454 Requesting a particular byte ordering may be necessary when you work with
455 binary data coming from some specific architecture whereas your program could
456 run on a totally different system. As an example, assume you have 24 bytes
457 containing a stack frame as it happens on an Intel 8086:
458 .PP
459 .Vb 11
460 \& +\-\-\-\-\-\-\-\-\-+ +\-\-\-\-+\-\-\-\-+ +\-\-\-\-\-\-\-\-\-+
461 \& TOS: | IP | TOS+4:| FL | FH | FLAGS TOS+14:| SI |
462 \& +\-\-\-\-\-\-\-\-\-+ +\-\-\-\-+\-\-\-\-+ +\-\-\-\-\-\-\-\-\-+
463 \& | CS | | AL | AH | AX | DI |
464 \& +\-\-\-\-\-\-\-\-\-+ +\-\-\-\-+\-\-\-\-+ +\-\-\-\-\-\-\-\-\-+
465 \& | BL | BH | BX | BP |
466 \& +\-\-\-\-+\-\-\-\-+ +\-\-\-\-\-\-\-\-\-+
467 \& | CL | CH | CX | DS |
468 \& +\-\-\-\-+\-\-\-\-+ +\-\-\-\-\-\-\-\-\-+
469 \& | DL | DH | DX | ES |
470 \& +\-\-\-\-+\-\-\-\-+ +\-\-\-\-\-\-\-\-\-+
471 .Ve
472 .PP
473 First, we note that this time\-honored 16\-bit CPU uses little\-endian order,
474 and that\*(Aqs why the low order byte is stored at the lower address. To
475 unpack such a (unsigned) short we\*(Aqll have to use code \f(CW\*(C`v\*(C'\fR. A repeat
476 count unpacks all 12 shorts:
477 .PP
478 .Vb 2
479 \& my( $ip, $cs, $flags, $ax, $bx, $cx, $dx, $si, $di, $bp, $ds, $es ) =
480 \& unpack( \*(Aqv12\*(Aq, $frame );
481 .Ve
482 .PP
483 Alternatively, we could have used \f(CW\*(C`C\*(C'\fR to unpack the individually
484 accessible byte registers FL, FH, AL, AH, etc.:
485 .PP
486 .Vb 2
487 \& my( $fl, $fh, $al, $ah, $bl, $bh, $cl, $ch, $dl, $dh ) =
488 \& unpack( \*(AqC10\*(Aq, substr( $frame, 4, 10 ) );
489 .Ve
490 .PP
491 It would be nice if we could do this in one fell swoop: unpack a short,
492 back up a little, and then unpack 2 bytes. Since Perl \fIis\fR nice, it
493 proffers the template code \f(CW\*(C`X\*(C'\fR to back up one byte. Putting this all
494 together, we may now write:
495 .PP
496 .Vb 5
497 \& my( $ip, $cs,
498 \& $flags,$fl,$fh,
499 \& $ax,$al,$ah, $bx,$bl,$bh, $cx,$cl,$ch, $dx,$dl,$dh,
500 \& $si, $di, $bp, $ds, $es ) =
501 \& unpack( \*(Aqv2\*(Aq . (\*(AqvXXCC\*(Aq x 5) . \*(Aqv5\*(Aq, $frame );
502 .Ve
503 .PP
504 (The clumsy construction of the template can be avoided \- just read on!)
505 .PP
506 We\*(Aqve taken some pains to construct the template so that it matches
507 the contents of our frame buffer. Otherwise we\*(Aqd either get undefined values,
508 or \f(CW\*(C`unpack\*(C'\fR could not unpack all. If \f(CW\*(C`pack\*(C'\fR runs out of items, it will
509 supply null strings (which are coerced into zeroes whenever the pack code
510 says so).
511 .SS "How to Eat an Egg on a Net"
512 .IX Subsection "How to Eat an Egg on a Net"
513 The pack code for big\-endian (high order byte at the lowest address) is
514 \&\f(CW\*(C`n\*(C'\fR for 16 bit and \f(CW\*(C`N\*(C'\fR for 32 bit integers. You use these codes
515 if you know that your data comes from a compliant architecture, but,
516 surprisingly enough, you should also use these pack codes if you
517 exchange binary data, across the network, with some system that you
518 know next to nothing about. The simple reason is that this
519 order has been chosen as the \fInetwork order\fR, and all standard\-fearing
520 programs ought to follow this convention. (This is, of course, a stern
521 backing for one of the Lilliputian parties and may well influence the
522 political development there.) So, if the protocol expects you to send
523 a message by sending the length first, followed by just so many bytes,
524 you could write:
525 .PP
526 .Vb 1
527 \& my $buf = pack( \*(AqN\*(Aq, length( $msg ) ) . $msg;
528 .Ve
529 .PP
530 or even:
531 .PP
532 .Vb 1
533 \& my $buf = pack( \*(AqNA*\*(Aq, length( $msg ), $msg );
534 .Ve
535 .PP
536 and pass \f(CW$buf\fR to your send routine. Some protocols demand that the
537 count should include the length of the count itself: then just add 4
538 to the data length. (But make sure to read "Lengths and Widths" before
539 you really code this!)
540 .SS "Byte\-order modifiers"
541 .IX Subsection "Byte-order modifiers"
542 In the previous sections we\*(Aqve learned how to use \f(CW\*(C`n\*(C'\fR, \f(CW\*(C`N\*(C'\fR, \f(CW\*(C`v\*(C'\fR and
543 \&\f(CW\*(C`V\*(C'\fR to pack and unpack integers with big\- or little\-endian byte\-order.
544 While this is nice, it\*(Aqs still rather limited because it leaves out all
545 kinds of signed integers as well as 64\-bit integers. For example, if you
546 wanted to unpack a sequence of signed big\-endian 16\-bit integers in a
547 platform\-independent way, you would have to write:
548 .PP
549 .Vb 1
550 \& my @data = unpack \*(Aqs*\*(Aq, pack \*(AqS*\*(Aq, unpack \*(Aqn*\*(Aq, $buf;
551 .Ve
552 .PP
553 This is ugly. As of Perl 5.9.2, there\*(Aqs a much nicer way to express your
554 desire for a certain byte\-order: the \f(CW\*(C`>\*(C'\fR and \f(CW\*(C`<\*(C'\fR modifiers.
555 \&\f(CW\*(C`>\*(C'\fR is the big\-endian modifier, while \f(CW\*(C`<\*(C'\fR is the little\-endian
556 modifier. Using them, we could rewrite the above code as:
557 .PP
558 .Vb 1
559 \& my @data = unpack \*(Aqs>*\*(Aq, $buf;
560 .Ve
561 .PP
562 As you can see, the "big end" of the arrow touches the \f(CW\*(C`s\*(C'\fR, which is a
563 nice way to remember that \f(CW\*(C`>\*(C'\fR is the big\-endian modifier. The same
564 obviously works for \f(CW\*(C`<\*(C'\fR, where the "little end" touches the code.
565 .PP
566 You will probably find these modifiers even more useful if you have
567 to deal with big\- or little\-endian C structures. Be sure to read
568 "Packing and Unpacking C Structures" for more on that.
569 .SS "Floating point Numbers"
570 .IX Subsection "Floating point Numbers"
571 For packing floating point numbers you have the choice between the
572 pack codes \f(CW\*(C`f\*(C'\fR, \f(CW\*(C`d\*(C'\fR, \f(CW\*(C`F\*(C'\fR and \f(CW\*(C`D\*(C'\fR. \f(CW\*(C`f\*(C'\fR and \f(CW\*(C`d\*(C'\fR pack into (or unpack
573 from) single\-precision or double\-precision representation as it is provided
574 by your system. If your system supports it, \f(CW\*(C`D\*(C'\fR can be used to pack and
575 unpack (\f(CW\*(C`long double\*(C'\fR) values, which can offer even more resolution
576 than \f(CW\*(C`f\*(C'\fR or \f(CW\*(C`d\*(C'\fR. \fBNote that there are different long double formats.\fR
577 .PP
578 \&\f(CW\*(C`F\*(C'\fR packs an \f(CW\*(C`NV\*(C'\fR, which is the floating point type used by Perl
579 internally.
580 .PP
581 There is no such thing as a network representation for reals, so if
582 you want to send your real numbers across computer boundaries, you\*(Aqd
583 better stick to text representation, possibly using the hexadecimal
584 float format (avoiding the decimal conversion loss), unless you\*(Aqre
585 absolutely sure what\*(Aqs on the other end of the line. For the even more
586 adventuresome, you can use the byte\-order modifiers from the previous
587 section also on floating point codes.
588 .SH "Exotic Templates"
589 .IX Header "Exotic Templates"
590 .SS "Bit Strings"
591 .IX Subsection "Bit Strings"
592 Bits are the atoms in the memory world. Access to individual bits may
593 have to be used either as a last resort or because it is the most
594 convenient way to handle your data. Bit string (un)packing converts
595 between strings containing a series of \f(CW0\fR and \f(CW1\fR characters and
596 a sequence of bytes each containing a group of 8 bits. This is almost
597 as simple as it sounds, except that there are two ways the contents of
598 a byte may be written as a bit string. Let\*(Aqs have a look at an annotated
599 byte:
600 .PP
601 .Vb 5
602 \& 7 6 5 4 3 2 1 0
603 \& +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+
604 \& | 1 0 0 0 1 1 0 0 |
605 \& +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+
606 \& MSB LSB
607 .Ve
608 .PP
609 It\*(Aqs egg\-eating all over again: Some think that as a bit string this should
610 be written "10001100" i.e. beginning with the most significant bit, others
611 insist on "00110001". Well, Perl isn\*(Aqt biased, so that\*(Aqs why we have two bit
612 string codes:
613 .PP
614 .Vb 2
615 \& $byte = pack( \*(AqB8\*(Aq, \*(Aq10001100\*(Aq ); # start with MSB
616 \& $byte = pack( \*(Aqb8\*(Aq, \*(Aq00110001\*(Aq ); # start with LSB
617 .Ve
618 .PP
619 It is not possible to pack or unpack bit fields \- just integral bytes.
620 \&\f(CW\*(C`pack\*(C'\fR always starts at the next byte boundary and "rounds up" to the
621 next multiple of 8 by adding zero bits as required. (If you do want bit
622 fields, there is "vec" in perlfunc. Or you could implement bit field
623 handling at the character string level, using split, substr, and
624 concatenation on unpacked bit strings.)
625 .PP
626 To illustrate unpacking for bit strings, we\*(Aqll decompose a simple
627 status register (a "\-" stands for a "reserved" bit):
628 .PP
629 .Vb 4
630 \& +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+
631 \& | S Z \- A \- P \- C | \- \- \- \- O D I T |
632 \& +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+
633 \& MSB LSB MSB LSB
634 .Ve
635 .PP
636 Converting these two bytes to a string can be done with the unpack
637 template \f(CW\*(Aqb16\*(Aq\fR. To obtain the individual bit values from the bit
638 string we use \f(CW\*(C`split\*(C'\fR with the "empty" separator pattern which dissects
639 into individual characters. Bit values from the "reserved" positions are
640 simply assigned to \f(CW\*(C`undef\*(C'\fR, a convenient notation for "I don\*(Aqt care where
641 this goes".
642 .PP
643 .Vb 3
644 \& ($carry, undef, $parity, undef, $auxcarry, undef, $zero, $sign,
645 \& $trace, $interrupt, $direction, $overflow) =
646 \& split( //, unpack( \*(Aqb16\*(Aq, $status ) );
647 .Ve
648 .PP
649 We could have used an unpack template \f(CW\*(Aqb12\*(Aq\fR just as well, since the
650 last 4 bits can be ignored anyway.
651 .SS Uuencoding
652 .IX Subsection "Uuencoding"
653 Another odd\-man\-out in the template alphabet is \f(CW\*(C`u\*(C'\fR, which packs a
654 "uuencoded string". ("uu" is short for Unix\-to\-Unix.) Chances are that
655 you won\*(Aqt ever need this encoding technique which was invented to overcome
656 the shortcomings of old\-fashioned transmission mediums that do not support
657 other than simple ASCII data. The essential recipe is simple: Take three
658 bytes, or 24 bits. Split them into 4 six\-packs, adding a space (0x20) to
659 each. Repeat until all of the data is blended. Fold groups of 4 bytes into
660 lines no longer than 60 and garnish them in front with the original byte count
661 (incremented by 0x20) and a \f(CW"\en"\fR at the end. \- The \f(CW\*(C`pack\*(C'\fR chef will
662 prepare this for you, a la minute, when you select pack code \f(CW\*(C`u\*(C'\fR on the menu:
663 .PP
664 .Vb 1
665 \& my $uubuf = pack( \*(Aqu\*(Aq, $bindat );
666 .Ve
667 .PP
668 A repeat count after \f(CW\*(C`u\*(C'\fR sets the number of bytes to put into an
669 uuencoded line, which is the maximum of 45 by default, but could be
670 set to some (smaller) integer multiple of three. \f(CW\*(C`unpack\*(C'\fR simply ignores
671 the repeat count.
672 .SS "Doing Sums"
673 .IX Subsection "Doing Sums"
674 An even stranger template code is \f(CW\*(C`%\*(C'\fR<\fInumber\fR>. First, because
675 it\*(Aqs used as a prefix to some other template code. Second, because it
676 cannot be used in \f(CW\*(C`pack\*(C'\fR at all, and third, in \f(CW\*(C`unpack\*(C'\fR, doesn\*(Aqt return the
677 data as defined by the template code it precedes. Instead it\*(Aqll give you an
678 integer of \fInumber\fR bits that is computed from the data value by
679 doing sums. For numeric unpack codes, no big feat is achieved:
680 .PP
681 .Vb 2
682 \& my $buf = pack( \*(Aqiii\*(Aq, 100, 20, 3 );
683 \& print unpack( \*(Aq%32i3\*(Aq, $buf ), "\en"; # prints 123
684 .Ve
685 .PP
686 For string values, \f(CW\*(C`%\*(C'\fR returns the sum of the byte values saving
687 you the trouble of a sum loop with \f(CW\*(C`substr\*(C'\fR and \f(CW\*(C`ord\*(C'\fR:
688 .PP
689 .Vb 1
690 \& print unpack( \*(Aq%32A*\*(Aq, "\ex01\ex10" ), "\en"; # prints 17
691 .Ve
692 .PP
693 Although the \f(CW\*(C`%\*(C'\fR code is documented as returning a "checksum":
694 don\*(Aqt put your trust in such values! Even when applied to a small number
695 of bytes, they won\*(Aqt guarantee a noticeable Hamming distance.
696 .PP
697 In connection with \f(CW\*(C`b\*(C'\fR or \f(CW\*(C`B\*(C'\fR, \f(CW\*(C`%\*(C'\fR simply adds bits, and this can be put
698 to good use to count set bits efficiently:
699 .PP
700 .Vb 1
701 \& my $bitcount = unpack( \*(Aq%32b*\*(Aq, $mask );
702 .Ve
703 .PP
704 And an even parity bit can be determined like this:
705 .PP
706 .Vb 1
707 \& my $evenparity = unpack( \*(Aq%1b*\*(Aq, $mask );
708 .Ve
709 .SS Unicode
710 .IX Subsection "Unicode"
711 Unicode is a character set that can represent most characters in most of
712 the world\*(Aqs languages, providing room for over one million different
713 characters. Unicode 3.1 specifies 94,140 characters: The Basic Latin
714 characters are assigned to the numbers 0 \- 127. The Latin\-1 Supplement with
715 characters that are used in several European languages is in the next
716 range, up to 255. After some more Latin extensions we find the character
717 sets from languages using non\-Roman alphabets, interspersed with a
718 variety of symbol sets such as currency symbols, Zapf Dingbats or Braille.
719 (You might want to visit <https://www.unicode.org/> for a look at some of
720 them \- my personal favourites are Telugu and Kannada.)
721 .PP
722 The Unicode character sets associates characters with integers. Encoding
723 these numbers in an equal number of bytes would more than double the
724 requirements for storing texts written in Latin alphabets.
725 The UTF\-8 encoding avoids this by storing the most common (from a western
726 point of view) characters in a single byte while encoding the rarer
727 ones in three or more bytes.
728 .PP
729 Perl uses UTF\-8, internally, for most Unicode strings.
730 .PP
731 So what has this got to do with \f(CW\*(C`pack\*(C'\fR? Well, if you want to compose a
732 Unicode string (that is internally encoded as UTF\-8), you can do so by
733 using template code \f(CW\*(C`U\*(C'\fR. As an example, let\*(Aqs produce the Euro currency
734 symbol (code number 0x20AC):
735 .PP
736 .Vb 2
737 \& $UTF8{Euro} = pack( \*(AqU\*(Aq, 0x20AC );
738 \& # Equivalent to: $UTF8{Euro} = "\ex{20ac}";
739 .Ve
740 .PP
741 Inspecting \f(CW$UTF8{Euro}\fR shows that it contains 3 bytes:
742 "\exe2\ex82\exac". However, it contains only 1 character, number 0x20AC.
743 The round trip can be completed with \f(CW\*(C`unpack\*(C'\fR:
744 .PP
745 .Vb 1
746 \& $Unicode{Euro} = unpack( \*(AqU\*(Aq, $UTF8{Euro} );
747 .Ve
748 .PP
749 Unpacking using the \f(CW\*(C`U\*(C'\fR template code also works on UTF\-8 encoded byte
750 strings.
751 .PP
752 Usually you\*(Aqll want to pack or unpack UTF\-8 strings:
753 .PP
754 .Vb 3
755 \& # pack and unpack the Hebrew alphabet
756 \& my $alefbet = pack( \*(AqU*\*(Aq, 0x05d0..0x05ea );
757 \& my @hebrew = unpack( \*(AqU*\*(Aq, $utf );
758 .Ve
759 .PP
760 Please note: in the general case, you\*(Aqre better off using
761 \&\f(CW\*(C`Encode::decode(\*(AqUTF\-8\*(Aq, $utf)\*(C'\fR to decode a UTF\-8
762 encoded byte string to a Perl Unicode string, and
763 \&\f(CW\*(C`Encode::encode(\*(AqUTF\-8\*(Aq, $str)\*(C'\fR to encode a Perl Unicode
764 string to UTF\-8 bytes. These functions provide means of handling invalid byte
765 sequences and generally have a friendlier interface.
766 .SS "Another Portable Binary Encoding"
767 .IX Subsection "Another Portable Binary Encoding"
768 The pack code \f(CW\*(C`w\*(C'\fR has been added to support a portable binary data
769 encoding scheme that goes way beyond simple integers. (Details can
770 be found at <https://github.com/mworks\-project/mw_scarab/blob/master/Scarab\-0.1.00d19/doc/binary\-serialization.txt>,
771 the Scarab project.) A BER (Binary Encoded
772 Representation) compressed unsigned integer stores base 128
773 digits, most significant digit first, with as few digits as possible.
774 Bit eight (the high bit) is set on each byte except the last. There
775 is no size limit to BER encoding, but Perl won\*(Aqt go to extremes.
776 .PP
777 .Vb 1
778 \& my $berbuf = pack( \*(Aqw*\*(Aq, 1, 128, 128+1, 128*128+127 );
779 .Ve
780 .PP
781 A hex dump of \f(CW$berbuf\fR, with spaces inserted at the right places,
782 shows 01 8100 8101 81807F. Since the last byte is always less than
783 128, \f(CW\*(C`unpack\*(C'\fR knows where to stop.
784 .SH "Template Grouping"
785 .IX Header "Template Grouping"
786 Prior to Perl 5.8, repetitions of templates had to be made by
787 \&\f(CW\*(C`x\*(C'\fR\-multiplication of template strings. Now there is a better way as
788 we may use the pack codes \f(CW\*(C`(\*(C'\fR and \f(CW\*(C`)\*(C'\fR combined with a repeat count.
789 The \f(CW\*(C`unpack\*(C'\fR template from the Stack Frame example can simply
790 be written like this:
791 .PP
792 .Vb 1
793 \& unpack( \*(Aqv2 (vXXCC)5 v5\*(Aq, $frame )
794 .Ve
795 .PP
796 Let\*(Aqs explore this feature a little more. We\*(Aqll begin with the equivalent of
797 .PP
798 .Vb 1
799 \& join( \*(Aq\*(Aq, map( substr( $_, 0, 1 ), @str ) )
800 .Ve
801 .PP
802 which returns a string consisting of the first character from each string.
803 Using pack, we can write
804 .PP
805 .Vb 1
806 \& pack( \*(Aq(A)\*(Aq.@str, @str )
807 .Ve
808 .PP
809 or, because a repeat count \f(CW\*(C`*\*(C'\fR means "repeat as often as required",
810 simply
811 .PP
812 .Vb 1
813 \& pack( \*(Aq(A)*\*(Aq, @str )
814 .Ve
815 .PP
816 (Note that the template \f(CW\*(C`A*\*(C'\fR would only have packed \f(CW$str[0]\fR in full
817 length.)
818 .PP
819 To pack dates stored as triplets ( day, month, year ) in an array \f(CW@dates\fR
820 into a sequence of byte, byte, short integer we can write
821 .PP
822 .Vb 1
823 \& $pd = pack( \*(Aq(CCS)*\*(Aq, map( @$_, @dates ) );
824 .Ve
825 .PP
826 To swap pairs of characters in a string (with even length) one could use
827 several techniques. First, let\*(Aqs use \f(CW\*(C`x\*(C'\fR and \f(CW\*(C`X\*(C'\fR to skip forward and back:
828 .PP
829 .Vb 1
830 \& $s = pack( \*(Aq(A)*\*(Aq, unpack( \*(Aq(xAXXAx)*\*(Aq, $s ) );
831 .Ve
832 .PP
833 We can also use \f(CW\*(C`@\*(C'\fR to jump to an offset, with 0 being the position where
834 we were when the last \f(CW\*(C`(\*(C'\fR was encountered:
835 .PP
836 .Vb 1
837 \& $s = pack( \*(Aq(A)*\*(Aq, unpack( \*(Aq(@1A @0A @2)*\*(Aq, $s ) );
838 .Ve
839 .PP
840 Finally, there is also an entirely different approach by unpacking big
841 endian shorts and packing them in the reverse byte order:
842 .PP
843 .Vb 1
844 \& $s = pack( \*(Aq(v)*\*(Aq, unpack( \*(Aq(n)*\*(Aq, $s );
845 .Ve
846 .SH "Lengths and Widths"
847 .IX Header "Lengths and Widths"
848 .SS "String Lengths"
849 .IX Subsection "String Lengths"
850 In the previous section we\*(Aqve seen a network message that was constructed
851 by prefixing the binary message length to the actual message. You\*(Aqll find
852 that packing a length followed by so many bytes of data is a
853 frequently used recipe since appending a null byte won\*(Aqt work
854 if a null byte may be part of the data. Here is an example where both
855 techniques are used: after two null terminated strings with source and
856 destination address, a Short Message (to a mobile phone) is sent after
857 a length byte:
858 .PP
859 .Vb 1
860 \& my $msg = pack( \*(AqZ*Z*CA*\*(Aq, $src, $dst, length( $sm ), $sm );
861 .Ve
862 .PP
863 Unpacking this message can be done with the same template:
864 .PP
865 .Vb 1
866 \& ( $src, $dst, $len, $sm ) = unpack( \*(AqZ*Z*CA*\*(Aq, $msg );
867 .Ve
868 .PP
869 There\*(Aqs a subtle trap lurking in the offing: Adding another field after
870 the Short Message (in variable \f(CW$sm\fR) is all right when packing, but this
871 cannot be unpacked naively:
872 .PP
873 .Vb 2
874 \& # pack a message
875 \& my $msg = pack( \*(AqZ*Z*CA*C\*(Aq, $src, $dst, length( $sm ), $sm, $prio );
876 \&
877 \& # unpack fails \- $prio remains undefined!
878 \& ( $src, $dst, $len, $sm, $prio ) = unpack( \*(AqZ*Z*CA*C\*(Aq, $msg );
879 .Ve
880 .PP
881 The pack code \f(CW\*(C`A*\*(C'\fR gobbles up all remaining bytes, and \f(CW$prio\fR remains
882 undefined! Before we let disappointment dampen the morale: Perl\*(Aqs got
883 the trump card to make this trick too, just a little further up the sleeve.
884 Watch this:
885 .PP
886 .Vb 2
887 \& # pack a message: ASCIIZ, ASCIIZ, length/string, byte
888 \& my $msg = pack( \*(AqZ* Z* C/A* C\*(Aq, $src, $dst, $sm, $prio );
889 \&
890 \& # unpack
891 \& ( $src, $dst, $sm, $prio ) = unpack( \*(AqZ* Z* C/A* C\*(Aq, $msg );
892 .Ve
893 .PP
894 Combining two pack codes with a slash (\f(CW\*(C`/\*(C'\fR) associates them with a single
895 value from the argument list. In \f(CW\*(C`pack\*(C'\fR, the length of the argument is
896 taken and packed according to the first code while the argument itself
897 is added after being converted with the template code after the slash.
898 This saves us the trouble of inserting the \f(CW\*(C`length\*(C'\fR call, but it is
899 in \f(CW\*(C`unpack\*(C'\fR where we really score: The value of the length byte marks the
900 end of the string to be taken from the buffer. Since this combination
901 doesn\*(Aqt make sense except when the second pack code isn\*(Aqt \f(CW\*(C`a*\*(C'\fR, \f(CW\*(C`A*\*(C'\fR
902 or \f(CW\*(C`Z*\*(C'\fR, Perl won\*(Aqt let you.
903 .PP
904 The pack code preceding \f(CW\*(C`/\*(C'\fR may be anything that\*(Aqs fit to represent a
905 number: All the numeric binary pack codes, and even text codes such as
906 \&\f(CW\*(C`A4\*(C'\fR or \f(CW\*(C`Z*\*(C'\fR:
907 .PP
908 .Vb 4
909 \& # pack/unpack a string preceded by its length in ASCII
910 \& my $buf = pack( \*(AqA4/A*\*(Aq, "Humpty\-Dumpty" );
911 \& # unpack $buf: \*(Aq13 Humpty\-Dumpty\*(Aq
912 \& my $txt = unpack( \*(AqA4/A*\*(Aq, $buf );
913 .Ve
914 .PP
915 \&\f(CW\*(C`/\*(C'\fR is not implemented in Perls before 5.6, so if your code is required to
916 work on ancient Perls you\*(Aqll need to \f(CW\*(C`unpack( \*(AqZ* Z* C\*(Aq)\*(C'\fR to get the length,
917 then use it to make a new unpack string. For example
918 .PP
919 .Vb 3
920 \& # pack a message: ASCIIZ, ASCIIZ, length, string, byte
921 \& # (5.005 compatible)
922 \& my $msg = pack( \*(AqZ* Z* C A* C\*(Aq, $src, $dst, length $sm, $sm, $prio );
923 \&
924 \& # unpack
925 \& ( undef, undef, $len) = unpack( \*(AqZ* Z* C\*(Aq, $msg );
926 \& ($src, $dst, $sm, $prio) = unpack ( "Z* Z* x A$len C", $msg );
927 .Ve
928 .PP
929 But that second \f(CW\*(C`unpack\*(C'\fR is rushing ahead. It isn\*(Aqt using a simple literal
930 string for the template. So maybe we should introduce...
931 .SS "Dynamic Templates"
932 .IX Subsection "Dynamic Templates"
933 So far, we\*(Aqve seen literals used as templates. If the list of pack
934 items doesn\*(Aqt have fixed length, an expression constructing the
935 template is required (whenever, for some reason, \f(CW\*(C`()*\*(C'\fR cannot be used).
936 Here\*(Aqs an example: To store named string values in a way that can be
937 conveniently parsed by a C program, we create a sequence of names and
938 null terminated ASCII strings, with \f(CW\*(C`=\*(C'\fR between the name and the value,
939 followed by an additional delimiting null byte. Here\*(Aqs how:
940 .PP
941 .Vb 2
942 \& my $env = pack( \*(Aq(A*A*Z*)\*(Aq . keys( %Env ) . \*(AqC\*(Aq,
943 \& map( { ( $_, \*(Aq=\*(Aq, $Env{$_} ) } keys( %Env ) ), 0 );
944 .Ve
945 .PP
946 Let\*(Aqs examine the cogs of this byte mill, one by one. There\*(Aqs the \f(CW\*(C`map\*(C'\fR
947 call, creating the items we intend to stuff into the \f(CW$env\fR buffer:
948 to each key (in \f(CW$_\fR) it adds the \f(CW\*(C`=\*(C'\fR separator and the hash entry value.
949 Each triplet is packed with the template code sequence \f(CW\*(C`A*A*Z*\*(C'\fR that
950 is repeated according to the number of keys. (Yes, that\*(Aqs what the \f(CW\*(C`keys\*(C'\fR
951 function returns in scalar context.) To get the very last null byte,
952 we add a \f(CW0\fR at the end of the \f(CW\*(C`pack\*(C'\fR list, to be packed with \f(CW\*(C`C\*(C'\fR.
953 (Attentive readers may have noticed that we could have omitted the 0.)
954 .PP
955 For the reverse operation, we\*(Aqll have to determine the number of items
956 in the buffer before we can let \f(CW\*(C`unpack\*(C'\fR rip it apart:
957 .PP
958 .Vb 2
959 \& my $n = $env =~ tr/\e0// \- 1;
960 \& my %env = map( split( /=/, $_ ), unpack( "(Z*)$n", $env ) );
961 .Ve
962 .PP
963 The \f(CW\*(C`tr\*(C'\fR counts the null bytes. The \f(CW\*(C`unpack\*(C'\fR call returns a list of
964 name\-value pairs each of which is taken apart in the \f(CW\*(C`map\*(C'\fR block.
965 .SS "Counting Repetitions"
966 .IX Subsection "Counting Repetitions"
967 Rather than storing a sentinel at the end of a data item (or a list of items),
968 we could precede the data with a count. Again, we pack keys and values of
969 a hash, preceding each with an unsigned short length count, and up front
970 we store the number of pairs:
971 .PP
972 .Vb 1
973 \& my $env = pack( \*(AqS(S/A* S/A*)*\*(Aq, scalar keys( %Env ), %Env );
974 .Ve
975 .PP
976 This simplifies the reverse operation as the number of repetitions can be
977 unpacked with the \f(CW\*(C`/\*(C'\fR code:
978 .PP
979 .Vb 1
980 \& my %env = unpack( \*(AqS/(S/A* S/A*)\*(Aq, $env );
981 .Ve
982 .PP
983 Note that this is one of the rare cases where you cannot use the same
984 template for \f(CW\*(C`pack\*(C'\fR and \f(CW\*(C`unpack\*(C'\fR because \f(CW\*(C`pack\*(C'\fR can\*(Aqt determine
985 a repeat count for a \f(CW\*(C`()\*(C'\fR\-group.
986 .SS "Intel HEX"
987 .IX Subsection "Intel HEX"
988 Intel HEX is a file format for representing binary data, mostly for
989 programming various chips, as a text file. (See
990 <https://en.wikipedia.org/wiki/.hex> for a detailed description, and
991 <https://en.wikipedia.org/wiki/SREC_(file_format)> for the Motorola
992 S\-record format, which can be unravelled using the same technique.)
993 Each line begins with a colon (\*(Aq:\*(Aq) and is followed by a sequence of
994 hexadecimal characters, specifying a byte count \fIn\fR (8 bit),
995 an address (16 bit, big endian), a record type (8 bit), \fIn\fR data bytes
996 and a checksum (8 bit) computed as the least significant byte of the two\*(Aqs
997 complement sum of the preceding bytes. Example: \f(CW\*(C`:0300300002337A1E\*(C'\fR.
998 .PP
999 The first step of processing such a line is the conversion, to binary,
1000 of the hexadecimal data, to obtain the four fields, while checking the
1001 checksum. No surprise here: we\*(Aqll start with a simple \f(CW\*(C`pack\*(C'\fR call to
1002 convert everything to binary:
1003 .PP
1004 .Vb 1
1005 \& my $binrec = pack( \*(AqH*\*(Aq, substr( $hexrec, 1 ) );
1006 .Ve
1007 .PP
1008 The resulting byte sequence is most convenient for checking the checksum.
1009 Don\*(Aqt slow your program down with a for loop adding the \f(CW\*(C`ord\*(C'\fR values
1010 of this string\*(Aqs bytes \- the \f(CW\*(C`unpack\*(C'\fR code \f(CW\*(C`%\*(C'\fR is the thing to use
1011 for computing the 8\-bit sum of all bytes, which must be equal to zero:
1012 .PP
1013 .Vb 1
1014 \& die unless unpack( "%8C*", $binrec ) == 0;
1015 .Ve
1016 .PP
1017 Finally, let\*(Aqs get those four fields. By now, you shouldn\*(Aqt have any
1018 problems with the first three fields \- but how can we use the byte count
1019 of the data in the first field as a length for the data field? Here
1020 the codes \f(CW\*(C`x\*(C'\fR and \f(CW\*(C`X\*(C'\fR come to the rescue, as they permit jumping
1021 back and forth in the string to unpack.
1022 .PP
1023 .Vb 1
1024 \& my( $addr, $type, $data ) = unpack( "x n C X4 C x3 /a", $bin );
1025 .Ve
1026 .PP
1027 Code \f(CW\*(C`x\*(C'\fR skips a byte, since we don\*(Aqt need the count yet. Code \f(CW\*(C`n\*(C'\fR takes
1028 care of the 16\-bit big\-endian integer address, and \f(CW\*(C`C\*(C'\fR unpacks the
1029 record type. Being at offset 4, where the data begins, we need the count.
1030 \&\f(CW\*(C`X4\*(C'\fR brings us back to square one, which is the byte at offset 0.
1031 Now we pick up the count, and zoom forth to offset 4, where we are
1032 now fully furnished to extract the exact number of data bytes, leaving
1033 the trailing checksum byte alone.
1034 .SH "Packing and Unpacking C Structures"
1035 .IX Header "Packing and Unpacking C Structures"
1036 In previous sections we have seen how to pack numbers and character
1037 strings. If it were not for a couple of snags we could conclude this
1038 section right away with the terse remark that C structures don\*(Aqt
1039 contain anything else, and therefore you already know all there is to it.
1040 Sorry, no: read on, please.
1041 .PP
1042 If you have to deal with a lot of C structures, and don\*(Aqt want to
1043 hack all your template strings manually, you\*(Aqll probably want to have
1044 a look at the CPAN module \f(CW\*(C`Convert::Binary::C\*(C'\fR. Not only can it parse
1045 your C source directly, but it also has built\-in support for all the
1046 odds and ends described further on in this section.
1047 .SS "The Alignment Pit"
1048 .IX Subsection "The Alignment Pit"
1049 In the consideration of speed against memory requirements the balance
1050 has been tilted in favor of faster execution. This has influenced the
1051 way C compilers allocate memory for structures: On architectures
1052 where a 16\-bit or 32\-bit operand can be moved faster between places in
1053 memory, or to or from a CPU register, if it is aligned at an even or
1054 multiple\-of\-four or even at a multiple\-of eight address, a C compiler
1055 will give you this speed benefit by stuffing extra bytes into structures.
1056 If you don\*(Aqt cross the C shoreline this is not likely to cause you any
1057 grief (although you should care when you design large data structures,
1058 or you want your code to be portable between architectures (you do want
1059 that, don\*(Aqt you?)).
1060 .PP
1061 To see how this affects \f(CW\*(C`pack\*(C'\fR and \f(CW\*(C`unpack\*(C'\fR, we\*(Aqll compare these two
1062 C structures:
1063 .PP
1064 .Vb 6
1065 \& typedef struct {
1066 \& char c1;
1067 \& short s;
1068 \& char c2;
1069 \& long l;
1070 \& } gappy_t;
1071 \&
1072 \& typedef struct {
1073 \& long l;
1074 \& short s;
1075 \& char c1;
1076 \& char c2;
1077 \& } dense_t;
1078 .Ve
1079 .PP
1080 Typically, a C compiler allocates 12 bytes to a \f(CW\*(C`gappy_t\*(C'\fR variable, but
1081 requires only 8 bytes for a \f(CW\*(C`dense_t\*(C'\fR. After investigating this further,
1082 we can draw memory maps, showing where the extra 4 bytes are hidden:
1083 .PP
1084 .Vb 5
1085 \& 0 +4 +8 +12
1086 \& +\-\-+\-\-+\-\-+\-\-+\-\-+\-\-+\-\-+\-\-+\-\-+\-\-+\-\-+\-\-+
1087 \& |c1|xx| s |c2|xx|xx|xx| l | xx = fill byte
1088 \& +\-\-+\-\-+\-\-+\-\-+\-\-+\-\-+\-\-+\-\-+\-\-+\-\-+\-\-+\-\-+
1089 \& gappy_t
1090 \&
1091 \& 0 +4 +8
1092 \& +\-\-+\-\-+\-\-+\-\-+\-\-+\-\-+\-\-+\-\-+
1093 \& | l | h |c1|c2|
1094 \& +\-\-+\-\-+\-\-+\-\-+\-\-+\-\-+\-\-+\-\-+
1095 \& dense_t
1096 .Ve
1097 .PP
1098 And that\*(Aqs where the first quirk strikes: \f(CW\*(C`pack\*(C'\fR and \f(CW\*(C`unpack\*(C'\fR
1099 templates have to be stuffed with \f(CW\*(C`x\*(C'\fR codes to get those extra fill bytes.
1100 .PP
1101 The natural question: "Why can\*(Aqt Perl compensate for the gaps?" warrants
1102 an answer. One good reason is that C compilers might provide (non\-ANSI)
1103 extensions permitting all sorts of fancy control over the way structures
1104 are aligned, even at the level of an individual structure field. And, if
1105 this were not enough, there is an insidious thing called \f(CW\*(C`union\*(C'\fR where
1106 the amount of fill bytes cannot be derived from the alignment of the next
1107 item alone.
1108 .PP
1109 OK, so let\*(Aqs bite the bullet. Here\*(Aqs one way to get the alignment right
1110 by inserting template codes \f(CW\*(C`x\*(C'\fR, which don\*(Aqt take a corresponding item
1111 from the list:
1112 .PP
1113 .Vb 1
1114 \& my $gappy = pack( \*(Aqcxs cxxx l!\*(Aq, $c1, $s, $c2, $l );
1115 .Ve
1116 .PP
1117 Note the \f(CW\*(C`!\*(C'\fR after \f(CW\*(C`l\*(C'\fR: We want to make sure that we pack a long
1118 integer as it is compiled by our C compiler. And even now, it will only
1119 work for the platforms where the compiler aligns things as above.
1120 And somebody somewhere has a platform where it doesn\*(Aqt.
1121 [Probably a Cray, where \f(CW\*(C`short\*(C'\fRs, \f(CW\*(C`int\*(C'\fRs and \f(CW\*(C`long\*(C'\fRs are all 8 bytes. :\-)]
1122 .PP
1123 Counting bytes and watching alignments in lengthy structures is bound to
1124 be a drag. Isn\*(Aqt there a way we can create the template with a simple
1125 program? Here\*(Aqs a C program that does the trick:
1126 .PP
1127 .Vb 2
1128 \& #include <stdio.h>
1129 \& #include <stddef.h>
1130 \&
1131 \& typedef struct {
1132 \& char fc1;
1133 \& short fs;
1134 \& char fc2;
1135 \& long fl;
1136 \& } gappy_t;
1137 \&
1138 \& #define Pt(struct,field,tchar) \e
1139 \& printf( "@%d%s ", offsetof(struct,field), # tchar );
1140 \&
1141 \& int main() {
1142 \& Pt( gappy_t, fc1, c );
1143 \& Pt( gappy_t, fs, s! );
1144 \& Pt( gappy_t, fc2, c );
1145 \& Pt( gappy_t, fl, l! );
1146 \& printf( "\en" );
1147 \& }
1148 .Ve
1149 .PP
1150 The output line can be used as a template in a \f(CW\*(C`pack\*(C'\fR or \f(CW\*(C`unpack\*(C'\fR call:
1151 .PP
1152 .Vb 1
1153 \& my $gappy = pack( \*(Aq@0c @2s! @4c @8l!\*(Aq, $c1, $s, $c2, $l );
1154 .Ve
1155 .PP
1156 Gee, yet another template code \- as if we hadn\*(Aqt plenty. But
1157 \&\f(CW\*(C`@\*(C'\fR saves our day by enabling us to specify the offset from the beginning
1158 of the pack buffer to the next item: This is just the value
1159 the \f(CW\*(C`offsetof\*(C'\fR macro (defined in \f(CW\*(C`<stddef.h>\*(C'\fR) returns when
1160 given a \f(CW\*(C`struct\*(C'\fR type and one of its field names ("member\-designator" in
1161 C standardese).
1162 .PP
1163 Neither using offsets nor adding \f(CW\*(C`x\*(C'\fR\*(Aqs to bridge the gaps is satisfactory.
1164 (Just imagine what happens if the structure changes.) What we really need
1165 is a way of saying "skip as many bytes as required to the next multiple of N".
1166 In fluent templates, you say this with \f(CW\*(C`x!N\*(C'\fR where N is replaced by the
1167 appropriate value. Here\*(Aqs the next version of our struct packaging:
1168 .PP
1169 .Vb 1
1170 \& my $gappy = pack( \*(Aqc x!2 s c x!4 l!\*(Aq, $c1, $s, $c2, $l );
1171 .Ve
1172 .PP
1173 That\*(Aqs certainly better, but we still have to know how long all the
1174 integers are, and portability is far away. Rather than \f(CW2\fR,
1175 for instance, we want to say "however long a short is". But this can be
1176 done by enclosing the appropriate pack code in brackets: \f(CW\*(C`[s]\*(C'\fR. So, here\*(Aqs
1177 the very best we can do:
1178 .PP
1179 .Vb 1
1180 \& my $gappy = pack( \*(Aqc x![s] s c x![l!] l!\*(Aq, $c1, $s, $c2, $l );
1181 .Ve
1182 .SS "Dealing with Endian\-ness"
1183 .IX Subsection "Dealing with Endian-ness"
1184 Now, imagine that we want to pack the data for a machine with a
1185 different byte\-order. First, we\*(Aqll have to figure out how big the data
1186 types on the target machine really are. Let\*(Aqs assume that the longs are
1187 32 bits wide and the shorts are 16 bits wide. You can then rewrite the
1188 template as:
1189 .PP
1190 .Vb 1
1191 \& my $gappy = pack( \*(Aqc x![s] s c x![l] l\*(Aq, $c1, $s, $c2, $l );
1192 .Ve
1193 .PP
1194 If the target machine is little\-endian, we could write:
1195 .PP
1196 .Vb 1
1197 \& my $gappy = pack( \*(Aqc x![s] s< c x![l] l<\*(Aq, $c1, $s, $c2, $l );
1198 .Ve
1199 .PP
1200 This forces the short and the long members to be little\-endian, and is
1201 just fine if you don\*(Aqt have too many struct members. But we could also
1202 use the byte\-order modifier on a group and write the following:
1203 .PP
1204 .Vb 1
1205 \& my $gappy = pack( \*(Aq( c x![s] s c x![l] l )<\*(Aq, $c1, $s, $c2, $l );
1206 .Ve
1207 .PP
1208 This is not as short as before, but it makes it more obvious that we
1209 intend to have little\-endian byte\-order for a whole group, not only
1210 for individual template codes. It can also be more readable and easier
1211 to maintain.
1212 .SS "Alignment, Take 2"
1213 .IX Subsection "Alignment, Take 2"
1214 I\*(Aqm afraid that we\*(Aqre not quite through with the alignment catch yet. The
1215 hydra raises another ugly head when you pack arrays of structures:
1216 .PP
1217 .Vb 4
1218 \& typedef struct {
1219 \& short count;
1220 \& char glyph;
1221 \& } cell_t;
1222 \&
1223 \& typedef cell_t buffer_t[BUFLEN];
1224 .Ve
1225 .PP
1226 Where\*(Aqs the catch? Padding is neither required before the first field \f(CW\*(C`count\*(C'\fR,
1227 nor between this and the next field \f(CW\*(C`glyph\*(C'\fR, so why can\*(Aqt we simply pack
1228 like this:
1229 .PP
1230 .Vb 3
1231 \& # something goes wrong here:
1232 \& pack( \*(Aqs!a\*(Aq x @buffer,
1233 \& map{ ( $_\->{count}, $_\->{glyph} ) } @buffer );
1234 .Ve
1235 .PP
1236 This packs \f(CW\*(C`3*@buffer\*(C'\fR bytes, but it turns out that the size of
1237 \&\f(CW\*(C`buffer_t\*(C'\fR is four times \f(CW\*(C`BUFLEN\*(C'\fR! The moral of the story is that
1238 the required alignment of a structure or array is propagated to the
1239 next higher level where we have to consider padding \fIat the end\fR
1240 of each component as well. Thus the correct template is:
1241 .PP
1242 .Vb 2
1243 \& pack( \*(Aqs!ax\*(Aq x @buffer,
1244 \& map{ ( $_\->{count}, $_\->{glyph} ) } @buffer );
1245 .Ve
1246 .SS "Alignment, Take 3"
1247 .IX Subsection "Alignment, Take 3"
1248 And even if you take all the above into account, ANSI still lets this:
1249 .PP
1250 .Vb 3
1251 \& typedef struct {
1252 \& char foo[2];
1253 \& } foo_t;
1254 .Ve
1255 .PP
1256 vary in size. The alignment constraint of the structure can be greater than
1257 any of its elements. [And if you think that this doesn\*(Aqt affect anything
1258 common, dismember the next cellphone that you see. Many have ARM cores, and
1259 the ARM structure rules make \f(CW\*(C`sizeof (foo_t)\*(C'\fR == 4]
1260 .SS "Pointers for How to Use Them"
1261 .IX Subsection "Pointers for How to Use Them"
1262 The title of this section indicates the second problem you may run into
1263 sooner or later when you pack C structures. If the function you intend
1264 to call expects a, say, \f(CW\*(C`void *\*(C'\fR value, you \fIcannot\fR simply take
1265 a reference to a Perl variable. (Although that value certainly is a
1266 memory address, it\*(Aqs not the address where the variable\*(Aqs contents are
1267 stored.)
1268 .PP
1269 Template code \f(CW\*(C`P\*(C'\fR promises to pack a "pointer to a fixed length string".
1270 Isn\*(Aqt this what we want? Let\*(Aqs try:
1271 .PP
1272 .Vb 3
1273 \& # allocate some storage and pack a pointer to it
1274 \& my $memory = "\ex00" x $size;
1275 \& my $memptr = pack( \*(AqP\*(Aq, $memory );
1276 .Ve
1277 .PP
1278 But wait: doesn\*(Aqt \f(CW\*(C`pack\*(C'\fR just return a sequence of bytes? How can we pass this
1279 string of bytes to some C code expecting a pointer which is, after all,
1280 nothing but a number? The answer is simple: We have to obtain the numeric
1281 address from the bytes returned by \f(CW\*(C`pack\*(C'\fR.
1282 .PP
1283 .Vb 1
1284 \& my $ptr = unpack( \*(AqL!\*(Aq, $memptr );
1285 .Ve
1286 .PP
1287 Obviously this assumes that it is possible to typecast a pointer
1288 to an unsigned long and vice versa, which frequently works but should not
1289 be taken as a universal law. \- Now that we have this pointer the next question
1290 is: How can we put it to good use? We need a call to some C function
1291 where a pointer is expected. The \fBread\fR\|(2) system call comes to mind:
1292 .PP
1293 .Vb 1
1294 \& ssize_t read(int fd, void *buf, size_t count);
1295 .Ve
1296 .PP
1297 After reading perlfunc explaining how to use \f(CW\*(C`syscall\*(C'\fR we can write
1298 this Perl function copying a file to standard output:
1299 .PP
1300 .Vb 12
1301 \& require \*(Aqsyscall.ph\*(Aq; # run h2ph to generate this file
1302 \& sub cat($){
1303 \& my $path = shift();
1304 \& my $size = \-s $path;
1305 \& my $memory = "\ex00" x $size; # allocate some memory
1306 \& my $ptr = unpack( \*(AqL\*(Aq, pack( \*(AqP\*(Aq, $memory ) );
1307 \& open( F, $path ) || die( "$path: cannot open ($!)\en" );
1308 \& my $fd = fileno(F);
1309 \& my $res = syscall( &SYS_read, fileno(F), $ptr, $size );
1310 \& print $memory;
1311 \& close( F );
1312 \& }
1313 .Ve
1314 .PP
1315 This is neither a specimen of simplicity nor a paragon of portability but
1316 it illustrates the point: We are able to sneak behind the scenes and
1317 access Perl\*(Aqs otherwise well\-guarded memory! (Important note: Perl\*(Aqs
1318 \&\f(CW\*(C`syscall\*(C'\fR does \fInot\fR require you to construct pointers in this roundabout
1319 way. You simply pass a string variable, and Perl forwards the address.)
1320 .PP
1321 How does \f(CW\*(C`unpack\*(C'\fR with \f(CW\*(C`P\*(C'\fR work? Imagine some pointer in the buffer
1322 about to be unpacked: If it isn\*(Aqt the null pointer (which will smartly
1323 produce the \f(CW\*(C`undef\*(C'\fR value) we have a start address \- but then what?
1324 Perl has no way of knowing how long this "fixed length string" is, so
1325 it\*(Aqs up to you to specify the actual size as an explicit length after \f(CW\*(C`P\*(C'\fR.
1326 .PP
1327 .Vb 2
1328 \& my $mem = "abcdefghijklmn";
1329 \& print unpack( \*(AqP5\*(Aq, pack( \*(AqP\*(Aq, $mem ) ); # prints "abcde"
1330 .Ve
1331 .PP
1332 As a consequence, \f(CW\*(C`pack\*(C'\fR ignores any number or \f(CW\*(C`*\*(C'\fR after \f(CW\*(C`P\*(C'\fR.
1333 .PP
1334 Now that we have seen \f(CW\*(C`P\*(C'\fR at work, we might as well give \f(CW\*(C`p\*(C'\fR a whirl.
1335 Why do we need a second template code for packing pointers at all? The
1336 answer lies behind the simple fact that an \f(CW\*(C`unpack\*(C'\fR with \f(CW\*(C`p\*(C'\fR promises
1337 a null\-terminated string starting at the address taken from the buffer,
1338 and that implies a length for the data item to be returned:
1339 .PP
1340 .Vb 2
1341 \& my $buf = pack( \*(Aqp\*(Aq, "abc\ex00efhijklmn" );
1342 \& print unpack( \*(Aqp\*(Aq, $buf ); # prints "abc"
1343 .Ve
1344 .PP
1345 Albeit this is apt to be confusing: As a consequence of the length being
1346 implied by the string\*(Aqs length, a number after pack code \f(CW\*(C`p\*(C'\fR is a repeat
1347 count, not a length as after \f(CW\*(C`P\*(C'\fR.
1348 .PP
1349 Using \f(CW\*(C`pack(..., $x)\*(C'\fR with \f(CW\*(C`P\*(C'\fR or \f(CW\*(C`p\*(C'\fR to get the address where \f(CW$x\fR is
1350 actually stored must be used with circumspection. Perl\*(Aqs internal machinery
1351 considers the relation between a variable and that address as its very own
1352 private matter and doesn\*(Aqt really care that we have obtained a copy. Therefore:
1353 .IP \(bu 4
1354 Do not use \f(CW\*(C`pack\*(C'\fR with \f(CW\*(C`p\*(C'\fR or \f(CW\*(C`P\*(C'\fR to obtain the address of variable
1355 that\*(Aqs bound to go out of scope (and thereby freeing its memory) before you
1356 are done with using the memory at that address.
1357 .IP \(bu 4
1358 Be very careful with Perl operations that change the value of the
1359 variable. Appending something to the variable, for instance, might require
1360 reallocation of its storage, leaving you with a pointer into no\-man\*(Aqs land.
1361 .IP \(bu 4
1362 Don\*(Aqt think that you can get the address of a Perl variable
1363 when it is stored as an integer or double number! \f(CW\*(C`pack(\*(AqP\*(Aq, $x)\*(C'\fR will
1364 force the variable\*(Aqs internal representation to string, just as if you
1365 had written something like \f(CW\*(C`$x .= \*(Aq\*(Aq\*(C'\fR.
1366 .PP
1367 It\*(Aqs safe, however, to P\- or p\-pack a string literal, because Perl simply
1368 allocates an anonymous variable.
1369 .SH "Pack Recipes"
1370 .IX Header "Pack Recipes"
1371 Here are a collection of (possibly) useful canned recipes for \f(CW\*(C`pack\*(C'\fR
1372 and \f(CW\*(C`unpack\*(C'\fR:
1373 .PP
1374 .Vb 2
1375 \& # Convert IP address for socket functions
1376 \& pack( "C4", split /\e./, "123.4.5.6" );
1377 \&
1378 \& # Count the bits in a chunk of memory (e.g. a select vector)
1379 \& unpack( \*(Aq%32b*\*(Aq, $mask );
1380 \&
1381 \& # Determine the endianness of your system
1382 \& $is_little_endian = unpack( \*(Aqc\*(Aq, pack( \*(Aqs\*(Aq, 1 ) );
1383 \& $is_big_endian = unpack( \*(Aqxc\*(Aq, pack( \*(Aqs\*(Aq, 1 ) );
1384 \&
1385 \& # Determine the number of bits in a native integer
1386 \& $bits = unpack( \*(Aq%32I!\*(Aq, ~0 );
1387 \&
1388 \& # Prepare argument for the nanosleep system call
1389 \& my $timespec = pack( \*(AqL!L!\*(Aq, $secs, $nanosecs );
1390 .Ve
1391 .PP
1392 For a simple memory dump we unpack some bytes into just as
1393 many pairs of hex digits, and use \f(CW\*(C`map\*(C'\fR to handle the traditional
1394 spacing \- 16 bytes to a line:
1395 .PP
1396 .Vb 4
1397 \& my $i;
1398 \& print map( ++$i % 16 ? "$_ " : "$_\en",
1399 \& unpack( \*(AqH2\*(Aq x length( $mem ), $mem ) ),
1400 \& length( $mem ) % 16 ? "\en" : \*(Aq\*(Aq;
1401 .Ve
1402 .SH "Funnies Section"
1403 .IX Header "Funnies Section"
1404 .Vb 5
1405 \& # Pulling digits out of nowhere...
1406 \& print unpack( \*(AqC\*(Aq, pack( \*(Aqx\*(Aq ) ),
1407 \& unpack( \*(Aq%B*\*(Aq, pack( \*(AqA\*(Aq ) ),
1408 \& unpack( \*(AqH\*(Aq, pack( \*(AqA\*(Aq ) ),
1409 \& unpack( \*(AqA\*(Aq, unpack( \*(AqC\*(Aq, pack( \*(AqA\*(Aq ) ) ), "\en";
1410 \&
1411 \& # One for the road ;\-)
1412 \& my $advice = pack( \*(Aqall u can in a van\*(Aq );
1413 .Ve
1414 .SH Authors
1415 .IX Header "Authors"
1416 Simon Cozens and Wolfgang Laun.