File: perlpacktut.html

package info (click to toggle)
perl-doc-html 5.18.2-1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 38,816 kB
  • ctags: 26,804
  • sloc: xml: 36; makefile: 10
file content (1311 lines) | stat: -rw-r--r-- 135,121 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <title>perlpacktut - perldoc.perl.org</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta http-equiv="Content-Language" content="en-gb">
  <link rel="search" type="application/opensearchdescription+xml" title="Search perldoc.perl.org" href="/static/search.xml"/>
  <link href="static/css-20100830.css" rel="stylesheet" rev="stylesheet" type="text/css" media="screen">
  <link href="static/exploreperl.css" rel="stylesheet" rev="stylesheet" type="text/css">
</head>

<body onLoad="perldoc.startup();" onPageShow="if (event.persisted) perldoc.startup();">
    <div id="page">
      
      <div id="header">
	<div id="homepage_link">
	  <a href="index.html"></a>
	</div>
	<div id="strapline">
	  Perl Programming Documentation
	</div>
	<div id="download_link" class="download">
	  <a href="http://www.perl.org/get.html">Download Perl</a>
	</div>
	<div id="explore_link" class="download">
	  <a id="explore_anchor" href="#">Explore</a>
	</div>
      </div>
      
      <div id="body">
        <div id="left_column">
          <div class="side_group">
            
	    <div class="side_panel doc_panel">
              <p>Manual</p>
              <ul>
                <li><a href="index-overview.html">Overview</a>
                <li><a href="index-tutorials.html">Tutorials</a>
                <li><a href="index-faq.html">FAQs</a>
                <li><a href="index-history.html">History / Changes</a>
                <li><a href="index-licence.html">License</a>
              </ul>
            </div>
            <div class="side_panel doc_panel">
              <p>Reference</p>
              <ul>
                <li><a href="index-language.html">Language</a>
                <li><a href="index-functions.html">Functions</a>
                <li><a href="perlop.html">Operators</a>
                <li><a href="perlvar.html">Special Variables</a>
                <li><a href="index-pragmas.html">Pragmas</a>
                <li><a href="index-utilities.html">Utilities</a>
                <li><a href="index-internals.html">Internals</a>
                <li><a href="index-platforms.html">Platform Specific</a>
              </ul>
            </div>
            <div class="side_panel doc_panel">
              <p>Modules</p>
              <ul>
		<li>
		
                
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		
                  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		
                  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		
                  
		
                  
		    
		  
		
                  
		
                  
		
		
                    <a href="index-modules-A.html">A</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-B.html">B</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-C.html">C</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-D.html">D</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-E.html">E</a>
                    
                      
                        <li>
                      
                    
                
                    <a href="index-modules-F.html">F</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-G.html">G</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-H.html">H</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-I.html">I</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-L.html">L</a>
                    
                      
                        <li>
                      
                    
                
                    <a href="index-modules-M.html">M</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-N.html">N</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-O.html">O</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-P.html">P</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-S.html">S</a>
                    
                      
                        <li>
                      
                    
                
                    <a href="index-modules-T.html">T</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-U.html">U</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-X.html">X</a>
                    
                
              </ul>
            </div>
            
	      <div class="side_panel doc_panel">
		<p>Tools</p>
		<ul>
		  <li><a href="preferences.html">Preferences</a>
		</ul>
	      </div>
            
          </div>
        </div>
        <div id="centre_column">
          <div id="content_header">
            <div id="title_bar">
              <div id="page_name">
                <h1>perlpacktut</h1>
              </div>
              <div id="perl_version">
                Perl 5 version 18.2 documentation
              </div>
              <div class="page_links" id="page_links_top">
                <a href="#" onClick="toolbar.goToTop();return false;">Go to top</a>
		
              </div>
	      <div class="page_links" id="page_links_bottom">
		
                  <a href="#" id="page_index_toggle">Show page index</a> &bull;
		
                <a href="#" id="recent_pages_toggle">Show recent pages</a>		
	      </div>
	      <div id="search_form">
		<form action="search.html" method="GET" id="search">
		  <input type="text" name="q" id="search_box" alt="Search">
		</form>
	      </div>
            </div>
            <div id="breadcrumbs">
                
    <a href="index.html">Home</a> &gt;
    
      
        <a href="index-tutorials.html">Tutorials</a> &gt;
      
    
    perlpacktut
  

            </div>
          </div>
          <div id="content_body">
	    <!--[if lt IE 7]>
 <div class="noscript">
   <p>
     <strong>It looks like you're using Internet Explorer 6. This is a very old
     browser which does not offer full support for modern websites.</strong>
   </p>
   <p>
     Unfortunately this means that this website will not work on
     your computer.
   </p>
   <p>
     Don't miss out though! To view the site (and get a better experience from
     many other websites), simply upgrade to
     <a href="http://www.microsoft.com/windows/Internet-explorer/default.aspx">Internet
Explorer 8</a>
     or download an alternative browser such as
     <a href="http://www.mozilla.com/en-US/firefox/firefox.html">Firefox</a>,
     <a href="http://www.apple.com/safari/download/">Safari</a>, or
     <a href="http://www.google.co.uk/chrome">Google Chrome</a>.
   </p>
   <p>
     All of these browsers are free. If you're using a PC at work, you may
     need to contact your IT administrator.
   </p>
 </div>
<![endif]-->
	    <noscript>
	      <div class="noscript">
	      <p>
                <strong>Please note: Many features of this site require JavaScript. You appear to have JavaScript disabled,
	        or are running a non-JavaScript capable web browser.</strong>
	      </p>
	      <p>
		To get the best experience, please enable JavaScript or download a modern web browser such as <a href="http://www.microsoft.com/windows/Internet-explorer/default.aspx">Internet Explorer 8</a>, <a href="http://www.mozilla.com/en-US/firefox/firefox.html">Firefox</a>, <a href="http://www.apple.com/safari/download/">Safari</a>, or <a href="http://www.google.co.uk/chrome">Google Chrome</a>.
              </p>
	      </div>
	    </noscript>

	    <div id="recent_pages" class="hud_container">
	      <div id="recent_pages_header" class="hud_header">
		<div id="recent_pages_close" class="hud_close"><a href="#" onClick="recentPages.hide();return false;"></a></div>
		<div id="recent_pages_title" class="hud_title"><span class="hud_span_top">Recently read</span></div>
		<div id="recent_pages_topright" class="hud_topright"></div>
	      </div>
	      <div id="recent_pages_content" class="hud_content">
	      </div>
	      <div id="recent_pages_footer" class="hud_footer">
		<div id="recent_pages_bottomleft" class="hud_bottomleft"></div>
		<div id="recent_pages_bottom" class="hud_bottom"><span class="hud_span_bottom"></span></div>
		<div id="recent_pages_resize" class="hud_resize"></div>
	      </div>
	    </div>
  
	    <div id="from_search"></div>
            <h1>perlpacktut</h1>


  <!--    -->
<ul><li><a href="#NAME">NAME</a><li><a href="#DESCRIPTION">DESCRIPTION</a><li><a href="#The-Basic-Principle">The Basic Principle</a><li><a href="#Packing-Text">Packing Text</a><li><a href="#Packing-Numbers">Packing Numbers</a><ul><li><a href="#Integers">Integers</a><li><a href="#Unpacking-a-Stack-Frame">Unpacking a Stack Frame</a><li><a href="#How-to-Eat-an-Egg-on-a-Net">How to Eat an Egg on a Net</a><li><a href="#Byte-order-modifiers">Byte-order modifiers</a><li><a href="#Floating-point-Numbers">Floating point Numbers</a></ul><li><a href="#Exotic-Templates">Exotic Templates</a><ul><li><a href="#Bit-Strings">Bit Strings</a><li><a href="#Uuencoding">Uuencoding</a><li><a href="#Doing-Sums">Doing Sums</a><li><a href="#Unicode">Unicode</a><li><a href="#Another-Portable-Binary-Encoding">Another Portable Binary Encoding</a></ul><li><a href="#Template-Grouping">Template Grouping</a><li><a href="#Lengths-and-Widths">Lengths and Widths</a><ul><li><a href="#String-Lengths">String Lengths</a><li><a href="#Dynamic-Templates">Dynamic Templates</a><li><a href="#Counting-Repetitions">Counting Repetitions</a><li><a href="#Intel-HEX">Intel HEX</a></ul><li><a href="#Packing-and-Unpacking-C-Structures">Packing and Unpacking C Structures</a><ul><li><a href="#The-Alignment-Pit">The Alignment Pit</a><li><a href="#Dealing-with-Endian-ness">Dealing with Endian-ness</a><li><a href="#Alignment%2c-Take-2">Alignment, Take 2</a><li><a href="#Alignment%2c-Take-3">Alignment, Take 3</a><li><a href="#Pointers-for-How-to-Use-Them">Pointers for How to Use Them</a></ul><li><a href="#Pack-Recipes">Pack Recipes</a><li><a href="#Funnies-Section">Funnies Section</a><li><a href="#Authors">Authors</a></ul><a name="NAME"></a><h1>NAME</h1>
<p>perlpacktut - tutorial on <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> and <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code></p>
<a name="DESCRIPTION"></a><h1>DESCRIPTION</h1>
<p><code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> and <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> are two functions for transforming data according
to a user-defined template, between the guarded way Perl stores values
and some well-defined representation as might be required in the 
environment of a Perl program. Unfortunately, they're also two of 
the most misunderstood and most often overlooked functions that Perl
provides. This tutorial will demystify them for you.</p>
<a name="The-Basic-Principle"></a><h1>The Basic Principle</h1>
<p>Most programming languages don't shelter the memory where variables are
stored. In C, for instance, you can take the address of some variable,
and the <code class="inline"><span class="w">sizeof</span></code>
 operator tells you how many bytes are allocated to
the variable. Using the address and the size, you may access the storage
to your heart's content.</p>
<p>In Perl, you just can't access memory at random, but the structural and
representational conversion provided by <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> and <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> is an
excellent alternative. The <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> function converts values to a byte
sequence containing representations according to a given specification,
the so-called "template" argument. <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> is the reverse process,
deriving some values from the contents of a string of bytes. (Be cautioned,
however, that not all that has been packed together can be neatly unpacked - 
a very common experience as seasoned travellers are likely to confirm.)</p>
<p>Why, you may ask, would you need a chunk of memory containing some values
in binary representation? One good reason is input and output accessing
some file, a device, or a network connection, whereby this binary
representation is either forced on you or will give you some benefit
in processing. Another cause is passing data to some system call that
is not available as a Perl function: <code class="inline"><a class="l_k" href="functions/syscall.html">syscall</a></code> requires you to provide
parameters stored in the way it happens in a C program. Even text processing 
(as shown in the next section) may be simplified with judicious usage 
of these two functions.</p>
<p>To see how (un)packing works, we'll start with a simple template
code where the conversion is in low gear: between the contents of a byte
sequence and a string of hexadecimal digits. Let's use <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code>, since
this is likely to remind you of a dump program, or some desperate last
message unfortunate programs are wont to throw at you before they expire
into the wild blue yonder. Assuming that the variable <code class="inline"><span class="i">$mem</span></code>
 holds a 
sequence of bytes that we'd like to inspect without assuming anything 
about its meaning, we can write</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/my.html">my</a><span class="s">(</span> <span class="i">$hex</span> <span class="s">)</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;H*&#39;</span><span class="cm">,</span> <span class="i">$mem</span> <span class="s">)</span><span class="sc">;</span></li><li>   <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;$hex\n&quot;</span><span class="sc">;</span></li></ol></pre><p>whereupon we might see something like this, with each pair of hex digits
corresponding to a byte:</p>
<pre class="verbatim"><ol><li>   41204d414e204120504c414e20412043414e414c2050414e414d41</li></ol></pre><p>What was in this chunk of memory? Numbers, characters, or a mixture of
both? Assuming that we're on a computer where ASCII (or some similar)
encoding is used: hexadecimal values in the range <code class="inline"><span class="n">0x40</span></code>
 - <code class="inline"><span class="n">0x5A</span></code>

indicate an uppercase letter, and <code class="inline"><span class="n">0x20</span></code>
 encodes a space. So we might
assume it is a piece of text, which some are able to read like a tabloid;
but others will have to get hold of an ASCII table and relive that
firstgrader feeling. Not caring too much about which way to read this,
we note that <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> with the template code <code class="inline"><span class="w">H</span></code>
 converts the contents
of a sequence of bytes into the customary hexadecimal notation. Since
"a sequence of" is a pretty vague indication of quantity, <code class="inline"><span class="w">H</span></code>
 has been
defined to convert just a single hexadecimal digit unless it is followed
by a repeat count. An asterisk for the repeat count means to use whatever
remains.</p>
<p>The inverse operation - packing byte contents from a string of hexadecimal
digits - is just as easily written. For instance:</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">$s</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;H2&#39;</span> x <span class="n">10</span><span class="cm">,</span> <span class="n">30</span>..<span class="n">39</span> <span class="s">)</span><span class="sc">;</span></li><li>   <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;$s\n&quot;</span><span class="sc">;</span></li></ol></pre><p>Since we feed a list of ten 2-digit hexadecimal strings to <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code>, the
pack template should contain ten pack codes. If this is run on a computer
with ASCII character coding, it will print <code class="inline"><span class="n">0123456789</span></code>
.</p>
<a name="Packing-Text"></a><h1>Packing Text</h1>
<p>Let's suppose you've got to read in a data file like this:</p>
<pre class="verbatim"><ol><li>    <span class="w">Date</span>      |<span class="w">Description</span>                | <span class="w">Income</span>|<span class="w">Expenditure</span></li><li>    <span class="n">01</span>/<span class="n">24</span>/<span class="n">2001</span> <span class="w">Zed&#39;s</span> <span class="w">Camel</span> <span class="w">Emporium</span>                    <span class="n">1147.99</span></li><li>    <span class="n">01</span>/<span class="n">28</span>/<span class="n">2001</span> <span class="w">Flea</span> <span class="w">spray</span>                                <span class="n">24.99</span></li><li>    <span class="n">01</span>/<span class="n">29</span>/<span class="n">2001</span> <span class="w">Camel</span> <span class="w">rides</span> <span class="w">to</span> <span class="w">tourists</span>      <span class="n">235.00</span></li></ol></pre><p>How do we do it? You might think first to use <code class="inline"><a class="l_k" href="functions/split.html">split</a></code>; however, since
<code class="inline"><a class="l_k" href="functions/split.html">split</a></code> collapses blank fields, you'll never know whether a record was
income or expenditure. Oops. Well, you could always use <code class="inline"><a class="l_k" href="functions/substr.html">substr</a></code>:</p>
<pre class="verbatim"><ol><li>    while <span class="s">(</span>&lt;&gt;<span class="s">)</span> <span class="s">{</span> </li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$date</span>   = <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span><span class="i">$_</span><span class="cm">,</span>  <span class="n">0</span><span class="cm">,</span> <span class="n">11</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$desc</span>   = <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span><span class="i">$_</span><span class="cm">,</span> <span class="n">12</span><span class="cm">,</span> <span class="n">27</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$income</span> = <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span><span class="i">$_</span><span class="cm">,</span> <span class="n">40</span><span class="cm">,</span>  <span class="n">7</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$expend</span> = <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span><span class="i">$_</span><span class="cm">,</span> <span class="n">52</span><span class="cm">,</span>  <span class="n">7</span><span class="s">)</span><span class="sc">;</span></li><li>        ...</li><li>    <span class="s">}</span></li></ol></pre><p>It's not really a barrel of laughs, is it? In fact, it's worse than it
may seem; the eagle-eyed may notice that the first field should only be
10 characters wide, and the error has propagated right through the other
numbers - which we've had to count by hand. So it's error-prone as well
as horribly unfriendly.</p>
<p>Or maybe we could use regular expressions:</p>
<pre class="verbatim"><ol><li>    while <span class="s">(</span>&lt;&gt;<span class="s">)</span> <span class="s">{</span> </li><li>        <a class="l_k" href="functions/my.html">my</a><span class="s">(</span><span class="i">$date</span><span class="cm">,</span> <span class="i">$desc</span><span class="cm">,</span> <span class="i">$income</span><span class="cm">,</span> <span class="i">$expend</span><span class="s">)</span> = </li><li>            <span class="q">m|(\d\d/\d\d/\d{4}) (.{27}) (.{7})(.*)|</span><span class="sc">;</span></li><li>        ...</li><li>    <span class="s">}</span></li></ol></pre><p>Urgh. Well, it's a bit better, but - well, would you want to maintain
that?</p>
<p>Hey, isn't Perl supposed to make this sort of thing easy? Well, it does,
if you use the right tools. <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> and <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> are designed to help
you out when dealing with fixed-width data like the above. Let's have a
look at a solution with <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code>:</p>
<pre class="verbatim"><ol><li>    while <span class="s">(</span>&lt;&gt;<span class="s">)</span> <span class="s">{</span> </li><li>        <a class="l_k" href="functions/my.html">my</a><span class="s">(</span><span class="i">$date</span><span class="cm">,</span> <span class="i">$desc</span><span class="cm">,</span> <span class="i">$income</span><span class="cm">,</span> <span class="i">$expend</span><span class="s">)</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span><span class="q">&quot;A10xA27xA7A*&quot;</span><span class="cm">,</span> <span class="i">$_</span><span class="s">)</span><span class="sc">;</span></li><li>        ...</li><li>    <span class="s">}</span></li></ol></pre><p>That looks a bit nicer; but we've got to take apart that weird template.
Where did I pull that out of?</p>
<p>OK, let's have a look at some of our data again; in fact, we'll include
the headers, and a handy ruler so we can keep track of where we are.</p>
<pre class="verbatim"><ol><li>             1         2         3         4         5        </li><li>    1234567890123456789012345678901234567890123456789012345678</li><li>    Date      |Description                | Income|Expenditure</li><li>    01/28/2001 Flea spray                                24.99</li><li>    01/29/2001 Camel rides to tourists      235.00</li></ol></pre><p>From this, we can see that the date column stretches from column 1 to
column 10 - ten characters wide. The <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code>-ese for "character" is
<code class="inline"><span class="w">A</span></code>
, and ten of them are <code class="inline"><span class="w">A10</span></code>
. So if we just wanted to extract the
dates, we could say this:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a><span class="s">(</span><span class="i">$date</span><span class="s">)</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span><span class="q">&quot;A10&quot;</span><span class="cm">,</span> <span class="i">$_</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>OK, what's next? Between the date and the description is a blank column;
we want to skip over that. The <code class="inline"><span class="w">x</span></code>
 template means "skip forward", so we
want one of those. Next, we have another batch of characters, from 12 to
38. That's 27 more characters, hence <code class="inline"><span class="w">A27</span></code>
. (Don't make the fencepost
error - there are 27 characters between 12 and 38, not 26. Count 'em!)</p>
<p>Now we skip another character and pick up the next 7 characters:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a><span class="s">(</span><span class="i">$date</span><span class="cm">,</span><span class="i">$description</span><span class="cm">,</span><span class="i">$income</span><span class="s">)</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span><span class="q">&quot;A10xA27xA7&quot;</span><span class="cm">,</span> <span class="i">$_</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Now comes the clever bit. Lines in our ledger which are just income and
not expenditure might end at column 46. Hence, we don't want to tell our
<code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> pattern that we <b>need</b> to find another 12 characters; we'll
just say "if there's anything left, take it". As you might guess from
regular expressions, that's what the <code class="inline"><span class="i">*</span></code>
 means: "use everything
remaining".</p>
<ul>
<li>
<p>Be warned, though, that unlike regular expressions, if the <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code>
template doesn't match the incoming data, Perl will scream and die.</p>
</li>
</ul>
<p>Hence, putting it all together:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a><span class="s">(</span><span class="i">$date</span><span class="cm">,</span><span class="i">$description</span><span class="cm">,</span><span class="i">$income</span><span class="cm">,</span><span class="i">$expend</span><span class="s">)</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span><span class="q">&quot;A10xA27xA7xA*&quot;</span><span class="cm">,</span> <span class="i">$_</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Now, that's our data parsed. I suppose what we might want to do now is
total up our income and expenditure, and add another line to the end of
our ledger - in the same format - saying how much we've brought in and
how much we've spent:</p>
<pre class="verbatim"><ol><li>    while <span class="s">(</span>&lt;&gt;<span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/my.html">my</a><span class="s">(</span><span class="i">$date</span><span class="cm">,</span> <span class="i">$desc</span><span class="cm">,</span> <span class="i">$income</span><span class="cm">,</span> <span class="i">$expend</span><span class="s">)</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span><span class="q">&quot;A10xA27xA7xA*&quot;</span><span class="cm">,</span> <span class="i">$_</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">$tot_income</span> += <span class="i">$income</span><span class="sc">;</span></li><li>        <span class="i">$tot_expend</span> += <span class="i">$expend</span><span class="sc">;</span></li><li>    <span class="s">}</span></li><li></li><li>    <span class="i">$tot_income</span> = <a class="l_k" href="functions/sprintf.html">sprintf</a><span class="s">(</span><span class="q">&quot;%.2f&quot;</span><span class="cm">,</span> <span class="i">$tot_income</span><span class="s">)</span><span class="sc">;</span> <span class="c"># Get them into </span></li><li>    <span class="i">$tot_expend</span> = <a class="l_k" href="functions/sprintf.html">sprintf</a><span class="s">(</span><span class="q">&quot;%.2f&quot;</span><span class="cm">,</span> <span class="i">$tot_expend</span><span class="s">)</span><span class="sc">;</span> <span class="c"># &quot;financial&quot; format</span></li><li></li><li>    <span class="i">$date</span> = <span class="i">POSIX::strftime</span><span class="s">(</span><span class="q">&quot;%m/%d/%Y&quot;</span><span class="cm">,</span> <a class="l_k" href="functions/localtime.html">localtime</a><span class="s">)</span><span class="sc">;</span> </li><li></li><li>    <span class="c"># OK, let&#39;s go:</span></li><li></li><li>    <a class="l_k" href="functions/print.html">print</a> <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span><span class="q">&quot;A10xA27xA7xA*&quot;</span><span class="cm">,</span> <span class="i">$date</span><span class="cm">,</span> <span class="q">&quot;Totals&quot;</span><span class="cm">,</span> <span class="i">$tot_income</span><span class="cm">,</span> <span class="i">$tot_expend</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Oh, hmm. That didn't quite work. Let's see what happened:</p>
<pre class="verbatim"><ol><li>    <span class="n">01</span>/<span class="n">24</span>/<span class="n">2001</span> <span class="w">Zed&#39;s</span> <span class="w">Camel</span> <span class="w">Emporium</span>                     <span class="n">1147.99</span></li><li>    <span class="n">01</span>/<span class="n">28</span>/<span class="n">2001</span> <span class="w">Flea</span> <span class="w">spray</span>                                 <span class="n">24.99</span></li><li>    <span class="n">01</span>/<span class="n">29</span>/<span class="n">2001</span> <span class="w">Camel</span> <span class="w">rides</span> <span class="w">to</span> <span class="w">tourists</span>     <span class="n">1235.00</span></li><li>    <span class="n">03</span>/<span class="n">23</span>/<span class="n">2001</span><span class="w">Totals</span>                     <span class="v">1235.001172.98</span></li></ol></pre><p>OK, it's a start, but what happened to the spaces? We put <code class="inline"><span class="w">x</span></code>
, didn't
we? Shouldn't it skip forward? Let's look at what <a href="functions/pack.html">pack</a> says:</p>
<pre class="verbatim"><ol><li>    <span class="w">x</span>   <span class="w">A</span> <span class="w">null</span> <span class="w">byte</span>.</li></ol></pre><p>Urgh. No wonder. There's a big difference between "a null byte",
character zero, and "a space", character 32. Perl's put something
between the date and the description - but unfortunately, we can't see
it!</p>
<p>What we actually need to do is expand the width of the fields. The <code class="inline"><span class="w">A</span></code>

format pads any non-existent characters with spaces, so we can use the
additional spaces to line up our fields, like this:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/print.html">print</a> <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span><span class="q">&quot;A11 A28 A8 A*&quot;</span><span class="cm">,</span> <span class="i">$date</span><span class="cm">,</span> <span class="q">&quot;Totals&quot;</span><span class="cm">,</span> <span class="i">$tot_income</span><span class="cm">,</span> <span class="i">$tot_expend</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>(Note that you can put spaces in the template to make it more readable,
but they don't translate to spaces in the output.) Here's what we got
this time:</p>
<pre class="verbatim"><ol><li>    <span class="n">01</span>/<span class="n">24</span>/<span class="n">2001</span> <span class="w">Zed&#39;s</span> <span class="w">Camel</span> <span class="w">Emporium</span>                     <span class="n">1147.99</span></li><li>    <span class="n">01</span>/<span class="n">28</span>/<span class="n">2001</span> <span class="w">Flea</span> <span class="w">spray</span>                                 <span class="n">24.99</span></li><li>    <span class="n">01</span>/<span class="n">29</span>/<span class="n">2001</span> <span class="w">Camel</span> <span class="w">rides</span> <span class="w">to</span> <span class="w">tourists</span>     <span class="n">1235.00</span></li><li>    <span class="n">03</span>/<span class="n">23</span>/<span class="n">2001</span> <span class="w">Totals</span>                      <span class="n">1235.00</span> <span class="n">1172.98</span></li></ol></pre><p>That's a bit better, but we still have that last column which needs to
be moved further over. There's an easy way to fix this up:
unfortunately, we can't get <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> to right-justify our fields, but we
can get <code class="inline"><a class="l_k" href="functions/sprintf.html">sprintf</a></code> to do it:</p>
<pre class="verbatim"><ol><li>    <span class="i">$tot_income</span> = <a class="l_k" href="functions/sprintf.html">sprintf</a><span class="s">(</span><span class="q">&quot;%.2f&quot;</span><span class="cm">,</span> <span class="i">$tot_income</span><span class="s">)</span><span class="sc">;</span> </li><li>    <span class="i">$tot_expend</span> = <a class="l_k" href="functions/sprintf.html">sprintf</a><span class="s">(</span><span class="q">&quot;%12.2f&quot;</span><span class="cm">,</span> <span class="i">$tot_expend</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$date</span> = <span class="i">POSIX::strftime</span><span class="s">(</span><span class="q">&quot;%m/%d/%Y&quot;</span><span class="cm">,</span> <a class="l_k" href="functions/localtime.html">localtime</a><span class="s">)</span><span class="sc">;</span> </li><li>    <a class="l_k" href="functions/print.html">print</a> <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span><span class="q">&quot;A11 A28 A8 A*&quot;</span><span class="cm">,</span> <span class="i">$date</span><span class="cm">,</span> <span class="q">&quot;Totals&quot;</span><span class="cm">,</span> <span class="i">$tot_income</span><span class="cm">,</span> <span class="i">$tot_expend</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>This time we get the right answer:</p>
<pre class="verbatim"><ol><li>    01/28/2001 Flea spray                                 24.99</li><li>    01/29/2001 Camel rides to tourists     1235.00</li><li>    03/23/2001 Totals                      1235.00      1172.98</li></ol></pre><p>So that's how we consume and produce fixed-width data. Let's recap what
we've seen of <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> and <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> so far:</p>
<ul>
<li>
<p>Use <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> to go from several pieces of data to one fixed-width
version; use <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> to turn a fixed-width-format string into several
pieces of data.</p>
</li>
<li>
<p>The pack format <code class="inline"><span class="w">A</span></code>
 means "any character"; if you're <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code>ing and
you've run out of things to pack, <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> will fill the rest up with
spaces.</p>
</li>
<li>
<p><code class="inline"><span class="w">x</span></code>
 means "skip a byte" when <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code>ing; when <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code>ing, it means
"introduce a null byte" - that's probably not what you mean if you're
dealing with plain text.</p>
</li>
<li>
<p>You can follow the formats with numbers to say how many characters
should be affected by that format: <code class="inline"><span class="w">A12</span></code>
 means "take 12 characters";
<code class="inline"><span class="w">x6</span></code>
 means "skip 6 bytes" or "character 0, 6 times".</p>
</li>
<li>
<p>Instead of a number, you can use <code class="inline"><span class="i">*</span></code>
 to mean "consume everything else
left".</p>
<p><b>Warning</b>: when packing multiple pieces of data, <code class="inline"><span class="i">*</span></code>
 only means
"consume all of the current piece of data". That's to say</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span><span class="q">&quot;A*A*&quot;</span><span class="cm">,</span> <span class="i">$one</span><span class="cm">,</span> <span class="i">$two</span><span class="s">)</span></li></ol></pre><p>packs all of <code class="inline"><span class="i">$one</span></code>
 into the first <code class="inline"><span class="w">A</span>*</code>
 and then all of <code class="inline"><span class="i">$two</span></code>
 into
the second. This is a general principle: each format character
corresponds to one piece of data to be <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code>ed.</p>
</li>
</ul>
<a name="Packing-Numbers"></a><h1>Packing Numbers</h1>
<p>So much for textual data. Let's get onto the meaty stuff that <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code>
and <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> are best at: handling binary formats for numbers. There is,
of course, not just one binary format  - life would be too simple - but
Perl will do all the finicky labor for you.</p>
<a name="Integers"></a><h2>Integers</h2>
<p>Packing and unpacking numbers implies conversion to and from some
<i>specific</i> binary representation. Leaving floating point numbers
aside for the moment, the salient properties of any such representation
are:</p>
<ul>
<li>
<p>the number of bytes used for storing the integer,</p>
</li>
<li>
<p>whether the contents are interpreted as a signed or unsigned number,</p>
</li>
<li>
<p>the byte ordering: whether the first byte is the least or most
significant byte (or: little-endian or big-endian, respectively).</p>
</li>
</ul>
<p>So, for instance, to pack 20302 to a signed 16 bit integer in your
computer's representation you write</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">$ps</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;s&#39;</span><span class="cm">,</span> <span class="n">20302</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Again, the result is a string, now containing 2 bytes. If you print 
this string (which is, generally, not recommended) you might see
<code class="inline"><span class="w">ON</span></code>
 or <code class="inline"><span class="w">NO</span></code>
 (depending on your system's byte ordering) - or something
entirely different if your computer doesn't use ASCII character encoding.
Unpacking <code class="inline"><span class="i">$ps</span></code>
 with the same template returns the original integer value:</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/my.html">my</a><span class="s">(</span> <span class="i">$s</span> <span class="s">)</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;s&#39;</span><span class="cm">,</span> <span class="i">$ps</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>This is true for all numeric template codes. But don't expect miracles:
if the packed value exceeds the allotted byte capacity, high order bits
are silently discarded, and unpack certainly won't be able to pull them
back out of some magic hat. And, when you pack using a signed template
code such as <code class="inline"><a class="l_k" href="functions/s.html">s</a></code>, an excess value may result in the sign bit
getting set, and unpacking this will smartly return a negative value.</p>
<p>16 bits won't get you too far with integers, but there is <code class="inline"><span class="w">l</span></code>
 and <code class="inline"><span class="w">L</span></code>

for signed and unsigned 32-bit integers. And if this is not enough and
your system supports 64 bit integers you can push the limits much closer
to infinity with pack codes <code class="inline"><a class="l_k" href="functions/q.html">q</a></code> and <code class="inline"><span class="w">Q</span></code>
. A notable exception is provided
by pack codes <code class="inline"><span class="w">i</span></code>
 and <code class="inline"><span class="w">I</span></code>
 for signed and unsigned integers of the 
"local custom" variety: Such an integer will take up as many bytes as
a local C compiler returns for <code class="inline"><span class="i">sizeof</span><span class="s">(</span><a class="l_k" href="functions/int.html">int</a><span class="s">)</span></code>
, but it'll use <i>at least</i>
32 bits.</p>
<p>Each of the integer pack codes <code class="inline"><span class="w">sSlLqQ</span></code>
 results in a fixed number of bytes,
no matter where you execute your program. This may be useful for some 
applications, but it does not provide for a portable way to pass data 
structures between Perl and C programs (bound to happen when you call 
XS extensions or the Perl function <code class="inline"><a class="l_k" href="functions/syscall.html">syscall</a></code>), or when you read or
write binary files. What you'll need in this case are template codes that
depend on what your local C compiler compiles when you code <code class="inline"><span class="w">short</span></code>
 or
<code class="inline"><span class="w">unsigned</span> <span class="w">long</span></code>
, for instance. These codes and their corresponding
byte lengths are shown in the table below.  Since the C standard leaves
much leeway with respect to the relative sizes of these data types, actual
values may vary, and that's why the values are given as expressions in
C and Perl. (If you'd like to use values from <code class="inline"><span class="i">%Config</span></code>
 in your program
you have to import it with <code class="inline"><a class="l_k" href="functions/use.html">use</a> <span class="w">Config</span></code>
.)</p>
<pre class="verbatim"><ol><li>   signed unsigned  byte length in C   byte length in Perl       </li><li>     s!     S!      sizeof(short)      $Config{shortsize}</li><li>     i!     I!      sizeof(int)        $Config{intsize}</li><li>     l!     L!      sizeof(long)       $Config{longsize}</li><li>     q!     Q!      sizeof(long long)  $Config{longlongsize}</li></ol></pre><p>The <code class="inline"><span class="w">i</span>!</code>
 and <code class="inline"><span class="w">I</span>!</code>
 codes aren't different from <code class="inline"><span class="w">i</span></code>
 and <code class="inline"><span class="w">I</span></code>
; they are
tolerated for completeness' sake.</p>
<a name="Unpacking-a-Stack-Frame"></a><h2>Unpacking a Stack Frame</h2>
<p>Requesting a particular byte ordering may be necessary when you work with
binary data coming from some specific architecture whereas your program could
run on a totally different system. As an example, assume you have 24 bytes
containing a stack frame as it happens on an Intel 8086:</p>
<pre class="verbatim"><ol><li>      +---------+        +----+----+               +---------+</li><li> TOS: |   IP    |  TOS+4:| FL | FH | FLAGS  TOS+14:|   SI    |</li><li>      +---------+        +----+----+               +---------+</li><li>      |   CS    |        | AL | AH | AX            |   DI    |</li><li>      +---------+        +----+----+               +---------+</li><li>                         | BL | BH | BX            |   BP    |</li><li>                         +----+----+               +---------+</li><li>                         | CL | CH | CX            |   DS    |</li><li>                         +----+----+               +---------+</li><li>                         | DL | DH | DX            |   ES    |</li><li>                         +----+----+               +---------+</li></ol></pre><p>First, we note that this time-honored 16-bit CPU uses little-endian order,
and that's why the low order byte is stored at the lower address. To
unpack such a (unsigned) short we'll have to use code <code class="inline"><span class="w">v</span></code>
. A repeat
count unpacks all 12 shorts:</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/my.html">my</a><span class="s">(</span> <span class="i">$ip</span><span class="cm">,</span> <span class="i">$cs</span><span class="cm">,</span> <span class="i">$flags</span><span class="cm">,</span> <span class="i">$ax</span><span class="cm">,</span> <span class="i">$bx</span><span class="cm">,</span> <span class="i">$cd</span><span class="cm">,</span> <span class="i">$dx</span><span class="cm">,</span> <span class="i">$si</span><span class="cm">,</span> <span class="i">$di</span><span class="cm">,</span> <span class="i">$bp</span><span class="cm">,</span> <span class="i">$ds</span><span class="cm">,</span> <span class="i">$es</span> <span class="s">)</span> =</li><li>     <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;v12&#39;</span><span class="cm">,</span> <span class="i">$frame</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Alternatively, we could have used <code class="inline"><span class="w">C</span></code>
 to unpack the individually
accessible byte registers FL, FH, AL, AH, etc.:</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/my.html">my</a><span class="s">(</span> <span class="i">$fl</span><span class="cm">,</span> <span class="i">$fh</span><span class="cm">,</span> <span class="i">$al</span><span class="cm">,</span> <span class="i">$ah</span><span class="cm">,</span> <span class="i">$bl</span><span class="cm">,</span> <span class="i">$bh</span><span class="cm">,</span> <span class="i">$cl</span><span class="cm">,</span> <span class="i">$ch</span><span class="cm">,</span> <span class="i">$dl</span><span class="cm">,</span> <span class="i">$dh</span> <span class="s">)</span> =</li><li>     <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;C10&#39;</span><span class="cm">,</span> <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span> <span class="i">$frame</span><span class="cm">,</span> <span class="n">4</span><span class="cm">,</span> <span class="n">10</span> <span class="s">)</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>It would be nice if we could do this in one fell swoop: unpack a short,
back up a little, and then unpack 2 bytes. Since Perl <i>is</i> nice, it
proffers the template code <code class="inline"><span class="w">X</span></code>
 to back up one byte. Putting this all
together, we may now write:</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/my.html">my</a><span class="s">(</span> <span class="i">$ip</span><span class="cm">,</span> <span class="i">$cs</span><span class="cm">,</span></li><li>       <span class="i">$flags</span><span class="cm">,</span><span class="i">$fl</span><span class="cm">,</span><span class="i">$fh</span><span class="cm">,</span></li><li>       <span class="i">$ax</span><span class="cm">,</span><span class="i">$al</span><span class="cm">,</span><span class="i">$ah</span><span class="cm">,</span> <span class="i">$bx</span><span class="cm">,</span><span class="i">$bl</span><span class="cm">,</span><span class="i">$bh</span><span class="cm">,</span> <span class="i">$cx</span><span class="cm">,</span><span class="i">$cl</span><span class="cm">,</span><span class="i">$ch</span><span class="cm">,</span> <span class="i">$dx</span><span class="cm">,</span><span class="i">$dl</span><span class="cm">,</span><span class="i">$dh</span><span class="cm">,</span> </li><li>       <span class="i">$si</span><span class="cm">,</span> <span class="i">$di</span><span class="cm">,</span> <span class="i">$bp</span><span class="cm">,</span> <span class="i">$ds</span><span class="cm">,</span> <span class="i">$es</span> <span class="s">)</span> =</li><li>   <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;v2&#39;</span> . <span class="s">(</span><span class="q">&#39;vXXCC&#39;</span> x <span class="n">5</span><span class="s">)</span> . <span class="q">&#39;v5&#39;</span><span class="cm">,</span> <span class="i">$frame</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>(The clumsy construction of the template can be avoided - just read on!)</p>
<p>We've taken some pains to construct the template so that it matches
the contents of our frame buffer. Otherwise we'd either get undefined values,
or <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> could not unpack all. If <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> runs out of items, it will
supply null strings (which are coerced into zeroes whenever the pack code
says so).</p>
<a name="How-to-Eat-an-Egg-on-a-Net"></a><h2>How to Eat an Egg on a Net</h2>
<p>The pack code for big-endian (high order byte at the lowest address) is
<code class="inline"><span class="w">n</span></code>
 for 16 bit and <code class="inline"><span class="w">N</span></code>
 for 32 bit integers. You use these codes
if you know that your data comes from a compliant architecture, but,
surprisingly enough, you should also use these pack codes if you
exchange binary data, across the network, with some system that you
know next to nothing about. The simple reason is that this
order has been chosen as the <i>network order</i>, and all standard-fearing
programs ought to follow this convention. (This is, of course, a stern
backing for one of the Lilliputian parties and may well influence the
political development there.) So, if the protocol expects you to send
a message by sending the length first, followed by just so many bytes,
you could write:</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">$buf</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;N&#39;</span><span class="cm">,</span> <a class="l_k" href="functions/length.html">length</a><span class="s">(</span> <span class="i">$msg</span> <span class="s">)</span> <span class="s">)</span> . <span class="i">$msg</span><span class="sc">;</span></li></ol></pre><p>or even:</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">$buf</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;NA*&#39;</span><span class="cm">,</span> <a class="l_k" href="functions/length.html">length</a><span class="s">(</span> <span class="i">$msg</span> <span class="s">)</span><span class="cm">,</span> <span class="i">$msg</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>and pass <code class="inline"><span class="i">$buf</span></code>
 to your send routine. Some protocols demand that the
count should include the length of the count itself: then just add 4
to the data length. (But make sure to read <a href="#Lengths-and-Widths">Lengths and Widths</a> before
you really code this!)</p>
<a name="Byte-order-modifiers"></a><h2>Byte-order modifiers</h2>
<p>In the previous sections we've learned how to use <code class="inline"><span class="w">n</span></code>
, <code class="inline"><span class="w">N</span></code>
, <code class="inline"><span class="w">v</span></code>
 and
<code class="inline"><span class="w">V</span></code>
 to pack and unpack integers with big- or little-endian byte-order.
While this is nice, it's still rather limited because it leaves out all
kinds of signed integers as well as 64-bit integers. For example, if you
wanted to unpack a sequence of signed big-endian 16-bit integers in a
platform-independent way, you would have to write:</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">@data</span> = <a class="l_k" href="functions/unpack.html">unpack</a> <span class="q">'s*'</span><span class="cm">,</span> <a class="l_k" href="functions/pack.html">pack</a> <span class="q">'S*'</span><span class="cm">,</span> <a class="l_k" href="functions/unpack.html">unpack</a> <span class="q">'n*'</span><span class="cm">,</span> <span class="i">$buf</span><span class="sc">;</span></li></ol></pre><p>This is ugly. As of Perl 5.9.2, there's a much nicer way to express your
desire for a certain byte-order: the <code class="inline">&gt;</code> and <code class="inline">&lt;</code>
 modifiers.
<code class="inline">&gt;</code> is the big-endian modifier, while <code class="inline">&lt;</code>
 is the little-endian
modifier. Using them, we could rewrite the above code as:</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">@data</span> = <a class="l_k" href="functions/unpack.html">unpack</a> <span class="q">'s&gt;*'</span><span class="cm">,</span> <span class="i">$buf</span><span class="sc">;</span></li></ol></pre><p>As you can see, the "big end" of the arrow touches the <code class="inline"><a class="l_k" href="functions/s.html">s</a></code>, which is a
nice way to remember that <code class="inline">&gt;</code> is the big-endian modifier. The same
obviously works for <code class="inline">&lt;</code>
, where the "little end" touches the code.</p>
<p>You will probably find these modifiers even more useful if you have
to deal with big- or little-endian C structures. Be sure to read
<a href="#Packing-and-Unpacking-C-Structures">Packing and Unpacking C Structures</a> for more on that.</p>
<a name="Floating-point-Numbers"></a><h2>Floating point Numbers</h2>
<p>For packing floating point numbers you have the choice between the
pack codes <code class="inline"><span class="w">f</span></code>
, <code class="inline"><span class="w">d</span></code>
, <code class="inline"><span class="w">F</span></code>
 and <code class="inline"><span class="w">D</span></code>
. <code class="inline"><span class="w">f</span></code>
 and <code class="inline"><span class="w">d</span></code>
 pack into (or unpack
from) single-precision or double-precision representation as it is provided
by your system. If your systems supports it, <code class="inline"><span class="w">D</span></code>
 can be used to pack and
unpack extended-precision floating point values (<code class="inline"><span class="w">long</span> <span class="w">double</span></code>
), which
can offer even more resolution than <code class="inline"><span class="w">f</span></code>
 or <code class="inline"><span class="w">d</span></code>
. <code class="inline"><span class="w">F</span></code>
 packs an <code class="inline"><span class="w">NV</span></code>
,
which is the floating point type used by Perl internally. (There
is no such thing as a network representation for reals, so if you want
to send your real numbers across computer boundaries, you'd better stick
to ASCII representation, unless you're absolutely sure what's on the other
end of the line. For the even more adventuresome, you can use the byte-order
modifiers from the previous section also on floating point codes.)</p>
<a name="Exotic-Templates"></a><h1>Exotic Templates</h1>
<a name="Bit-Strings"></a><h2>Bit Strings</h2>
<p>Bits are the atoms in the memory world. Access to individual bits may
have to be used either as a last resort or because it is the most
convenient way to handle your data. Bit string (un)packing converts
between strings containing a series of <code class="inline"><span class="n">0</span></code>
 and <code class="inline"><span class="n">1</span></code>
 characters and
a sequence of bytes each containing a group of 8 bits. This is almost
as simple as it sounds, except that there are two ways the contents of
a byte may be written as a bit string. Let's have a look at an annotated
byte:</p>
<pre class="verbatim"><ol><li>     7 6 5 4 3 2 1 0</li><li>   +-----------------+</li><li>   | 1 0 0 0 1 1 0 0 |</li><li>   +-----------------+</li><li>    MSB           LSB</li></ol></pre><p>It's egg-eating all over again: Some think that as a bit string this should
be written "10001100" i.e. beginning with the most significant bit, others
insist on "00110001". Well, Perl isn't biased, so that's why we have two bit
string codes:</p>
<pre class="verbatim"><ol><li>   <span class="i">$byte</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;B8&#39;</span><span class="cm">,</span> <span class="q">&#39;10001100&#39;</span> <span class="s">)</span><span class="sc">;</span> <span class="c"># start with MSB</span></li><li>   <span class="i">$byte</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;b8&#39;</span><span class="cm">,</span> <span class="q">&#39;00110001&#39;</span> <span class="s">)</span><span class="sc">;</span> <span class="c"># start with LSB</span></li></ol></pre><p>It is not possible to pack or unpack bit fields - just integral bytes.
<code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> always starts at the next byte boundary and "rounds up" to the
next multiple of 8 by adding zero bits as required. (If you do want bit
fields, there is <a href="functions/vec.html">vec</a>. Or you could implement bit field 
handling at the character string level, using split, substr, and
concatenation on unpacked bit strings.)</p>
<p>To illustrate unpacking for bit strings, we'll decompose a simple
status register (a "-" stands for a "reserved" bit):</p>
<pre class="verbatim"><ol><li>   +-----------------+-----------------+</li><li>   | S Z - A - P - C | - - - - O D I T |</li><li>   +-----------------+-----------------+</li><li>    MSB           LSB MSB           LSB</li></ol></pre><p>Converting these two bytes to a string can be done with the unpack 
template <code class="inline"><span class="q">&#39;b16&#39;</span></code>
. To obtain the individual bit values from the bit
string we use <code class="inline"><a class="l_k" href="functions/split.html">split</a></code> with the "empty" separator pattern which dissects
into individual characters. Bit values from the "reserved" positions are
simply assigned to <code class="inline"><a class="l_k" href="functions/undef.html">undef</a></code>, a convenient notation for "I don't care where
this goes".</p>
<pre class="verbatim"><ol><li>   <span class="s">(</span><span class="i">$carry</span><span class="cm">,</span> <a class="l_k" href="functions/undef.html">undef</a><span class="cm">,</span> <span class="i">$parity</span><span class="cm">,</span> <a class="l_k" href="functions/undef.html">undef</a><span class="cm">,</span> <span class="i">$auxcarry</span><span class="cm">,</span> <a class="l_k" href="functions/undef.html">undef</a><span class="cm">,</span> <span class="i">$zero</span><span class="cm">,</span> <span class="i">$sign</span><span class="cm">,</span></li><li>    <span class="i">$trace</span><span class="cm">,</span> <span class="i">$interrupt</span><span class="cm">,</span> <span class="i">$direction</span><span class="cm">,</span> <span class="i">$overflow</span><span class="s">)</span> =</li><li>      <a class="l_k" href="functions/split.html">split</a><span class="s">(</span> <span class="q">//</span><span class="cm">,</span> <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;b16&#39;</span><span class="cm">,</span> <span class="i">$status</span> <span class="s">)</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>We could have used an unpack template <code class="inline"><span class="q">&#39;b12&#39;</span></code>
 just as well, since the
last 4 bits can be ignored anyway.</p>
<a name="Uuencoding"></a><h2>Uuencoding</h2>
<p>Another odd-man-out in the template alphabet is <code class="inline"><span class="w">u</span></code>
, which packs an
"uuencoded string". ("uu" is short for Unix-to-Unix.) Chances are that
you won't ever need this encoding technique which was invented to overcome
the shortcomings of old-fashioned transmission mediums that do not support
other than simple ASCII data. The essential recipe is simple: Take three 
bytes, or 24 bits. Split them into 4 six-packs, adding a space (0x20) to 
each. Repeat until all of the data is blended. Fold groups of 4 bytes into 
lines no longer than 60 and garnish them in front with the original byte count 
(incremented by 0x20) and a <code class="inline"><span class="q">&quot;\n&quot;</span></code>
 at the end. - The <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> chef will
prepare this for you, a la minute, when you select pack code <code class="inline"><span class="w">u</span></code>
 on the menu:</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">$uubuf</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;u&#39;</span><span class="cm">,</span> <span class="i">$bindat</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>A repeat count after <code class="inline"><span class="w">u</span></code>
 sets the number of bytes to put into an
uuencoded line, which is the maximum of 45 by default, but could be
set to some (smaller) integer multiple of three. <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> simply ignores
the repeat count.</p>
<a name="Doing-Sums"></a><h2>Doing Sums</h2>
<p>An even stranger template code is <code class="inline"><span class="i">%</span></code>
&lt;<i>number</i>&gt;. First, because 
it's used as a prefix to some other template code. Second, because it
cannot be used in <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> at all, and third, in <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code>, doesn't return the
data as defined by the template code it precedes. Instead it'll give you an
integer of <i>number</i> bits that is computed from the data value by 
doing sums. For numeric unpack codes, no big feat is achieved:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$buf</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;iii&#39;</span><span class="cm">,</span> <span class="n">100</span><span class="cm">,</span> <span class="n">20</span><span class="cm">,</span> <span class="n">3</span> <span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/print.html">print</a> <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;%32i3&#39;</span><span class="cm">,</span> <span class="i">$buf</span> <span class="s">)</span><span class="cm">,</span> <span class="q">&quot;\n&quot;</span><span class="sc">;</span>  <span class="c"># prints 123</span></li></ol></pre><p>For string values, <code class="inline"><span class="i">%</span></code>
 returns the sum of the byte values saving
you the trouble of a sum loop with <code class="inline"><a class="l_k" href="functions/substr.html">substr</a></code> and <code class="inline"><a class="l_k" href="functions/ord.html">ord</a></code>:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/print.html">print</a> <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;%32A*&#39;</span><span class="cm">,</span> <span class="q">&quot;\x01\x10&quot;</span> <span class="s">)</span><span class="cm">,</span> <span class="q">&quot;\n&quot;</span><span class="sc">;</span>  <span class="c"># prints 17</span></li></ol></pre><p>Although the <code class="inline"><span class="i">%</span></code>
 code is documented as returning a "checksum":
don't put your trust in such values! Even when applied to a small number
of bytes, they won't guarantee a noticeable Hamming distance.</p>
<p>In connection with <code class="inline"><span class="w">b</span></code>
 or <code class="inline"><span class="w">B</span></code>
, <code class="inline"><span class="i">%</span></code>
 simply adds bits, and this can be put
to good use to count set bits efficiently:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$bitcount</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;%32b*&#39;</span><span class="cm">,</span> <span class="i">$mask</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>And an even parity bit can be determined like this:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$evenparity</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;%1b*&#39;</span><span class="cm">,</span> <span class="i">$mask</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><a name="Unicode"></a><h2>Unicode</h2>
<p>Unicode is a character set that can represent most characters in most of
the world's languages, providing room for over one million different
characters. Unicode 3.1 specifies 94,140 characters: The Basic Latin
characters are assigned to the numbers 0 - 127. The Latin-1 Supplement with
characters that are used in several European languages is in the next
range, up to 255. After some more Latin extensions we find the character
sets from languages using non-Roman alphabets, interspersed with a
variety of symbol sets such as currency symbols, Zapf Dingbats or Braille.
(You might want to visit <a href="http://www.unicode.org/">http://www.unicode.org/</a> for a look at some of
them - my personal favourites are Telugu and Kannada.)</p>
<p>The Unicode character sets associates characters with integers. Encoding
these numbers in an equal number of bytes would more than double the
requirements for storing texts written in Latin alphabets.
The UTF-8 encoding avoids this by storing the most common (from a western
point of view) characters in a single byte while encoding the rarer
ones in three or more bytes.</p>
<p>Perl uses UTF-8, internally, for most Unicode strings.</p>
<p>So what has this got to do with <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code>? Well, if you want to compose a
Unicode string (that is internally encoded as UTF-8), you can do so by
using template code <code class="inline"><span class="w">U</span></code>
. As an example, let's produce the Euro currency
symbol (code number 0x20AC):</p>
<pre class="verbatim"><ol><li>   <span class="i">$UTF8</span>{<span class="w">Euro</span>} = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">'U'</span><span class="cm">,</span> <span class="n">0x20AC</span> <span class="s">)</span><span class="sc">;</span></li><li>   <span class="c"># Equivalent to: $UTF8{Euro} = &quot;\x{20ac}&quot;;</span></li></ol></pre><p>Inspecting <code class="inline"><span class="i">$UTF8</span>{<span class="w">Euro</span>}</code>
 shows that it contains 3 bytes:
"\xe2\x82\xac". However, it contains only 1 character, number 0x20AC.
The round trip can be completed with <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code>:</p>
<pre class="verbatim"><ol><li>   <span class="i">$Unicode</span>{<span class="w">Euro</span>} = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;U&#39;</span><span class="cm">,</span> <span class="i">$UTF8</span>{<span class="w">Euro</span>} <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Unpacking using the <code class="inline"><span class="w">U</span></code>
 template code also works on UTF-8 encoded byte
strings.</p>
<p>Usually you'll want to pack or unpack UTF-8 strings:</p>
<pre class="verbatim"><ol><li>   <span class="c"># pack and unpack the Hebrew alphabet</span></li><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">$alefbet</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;U*&#39;</span><span class="cm">,</span> <span class="n">0x05d0</span>..<span class="n">0x05ea</span> <span class="s">)</span><span class="sc">;</span></li><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">@hebrew</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;U*&#39;</span><span class="cm">,</span> <span class="i">$utf</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Please note: in the general case, you're better off using
Encode::decode_utf8 to decode a UTF-8 encoded byte string to a Perl
Unicode string, and Encode::encode_utf8 to encode a Perl Unicode string
to UTF-8 bytes. These functions provide means of handling invalid byte
sequences and generally have a friendlier interface.</p>
<a name="Another-Portable-Binary-Encoding"></a><h2>Another Portable Binary Encoding</h2>
<p>The pack code <code class="inline"><span class="w">w</span></code>
 has been added to support a portable binary data
encoding scheme that goes way beyond simple integers. (Details can
be found at <a href="http://Casbah.org/">http://Casbah.org/</a>, the Scarab project.)  A BER (Binary Encoded
Representation) compressed unsigned integer stores base 128
digits, most significant digit first, with as few digits as possible.
Bit eight (the high bit) is set on each byte except the last. There
is no size limit to BER encoding, but Perl won't go to extremes.</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">$berbuf</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;w*&#39;</span><span class="cm">,</span> <span class="n">1</span><span class="cm">,</span> <span class="n">128</span><span class="cm">,</span> <span class="n">128</span>+<span class="n">1</span><span class="cm">,</span> <span class="n">128</span>*<span class="n">128</span>+<span class="n">127</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>A hex dump of <code class="inline"><span class="i">$berbuf</span></code>
, with spaces inserted at the right places,
shows 01 8100 8101 81807F. Since the last byte is always less than
128, <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> knows where to stop.</p>
<a name="Template-Grouping"></a><h1>Template Grouping</h1>
<p>Prior to Perl 5.8, repetitions of templates had to be made by
<code class="inline"><span class="w">x</span></code>
-multiplication of template strings. Now there is a better way as
we may use the pack codes <code class="inline">(</code> and <code class="inline">)</code> combined with a repeat count.
The <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> template from the Stack Frame example can simply
be written like this:</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;v2 (vXXCC)5 v5&#39;</span><span class="cm">,</span> <span class="i">$frame</span> <span class="s">)</span></li></ol></pre><p>Let's explore this feature a little more. We'll begin with the equivalent of</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/join.html">join</a><span class="s">(</span> <span class="q">&#39;&#39;</span><span class="cm">,</span> <a class="l_k" href="functions/map.html">map</a><span class="s">(</span> <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span> <span class="i">$_</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="n">1</span> <span class="s">)</span><span class="cm">,</span> <span class="i">@str</span> <span class="s">)</span> <span class="s">)</span></li></ol></pre><p>which returns a string consisting of the first character from each string.
Using pack, we can write</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;(A)&#39;</span>.<span class="i">@str</span><span class="cm">,</span> <span class="i">@str</span> <span class="s">)</span></li></ol></pre><p>or, because a repeat count <code class="inline"><span class="i">*</span></code>
 means "repeat as often as required",
simply</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;(A)*&#39;</span><span class="cm">,</span> <span class="i">@str</span> <span class="s">)</span></li></ol></pre><p>(Note that the template <code class="inline"><span class="w">A</span>*</code>
 would only have packed <code class="inline"><span class="i">$str</span>[<span class="n">0</span>]</code>
 in full
length.)</p>
<p>To pack dates stored as triplets ( day, month, year ) in an array <code class="inline"><span class="i">@dates</span></code>

into a sequence of byte, byte, short integer we can write</p>
<pre class="verbatim"><ol><li>   <span class="i">$pd</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;(CCS)*&#39;</span><span class="cm">,</span> <a class="l_k" href="functions/map.html">map</a><span class="s">(</span> <span class="i">@$_</span><span class="cm">,</span> <span class="i">@dates</span> <span class="s">)</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>To swap pairs of characters in a string (with even length) one could use
several techniques. First, let's use <code class="inline"><span class="w">x</span></code>
 and <code class="inline"><span class="w">X</span></code>
 to skip forward and back:</p>
<pre class="verbatim"><ol><li>   <span class="i">$s</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;(A)*&#39;</span><span class="cm">,</span> <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;(xAXXAx)*&#39;</span><span class="cm">,</span> <span class="i">$s</span> <span class="s">)</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>We can also use <code class="inline"><span class="i">@</span></code>
 to jump to an offset, with 0 being the position where
we were when the last <code class="inline">(</code> was encountered:</p>
<pre class="verbatim"><ol><li>   <span class="i">$s</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;(A)*&#39;</span><span class="cm">,</span> <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;(@1A @0A @2)*&#39;</span><span class="cm">,</span> <span class="i">$s</span> <span class="s">)</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Finally, there is also an entirely different approach by unpacking big
endian shorts and packing them in the reverse byte order:</p>
<pre class="verbatim"><ol><li>   $s = pack( '(v)*', unpack( '(n)*', $s );</li></ol></pre><a name="Lengths-and-Widths"></a><h1>Lengths and Widths</h1>
<a name="String-Lengths"></a><h2>String Lengths</h2>
<p>In the previous section we've seen a network message that was constructed
by prefixing the binary message length to the actual message. You'll find
that packing a length followed by so many bytes of data is a 
frequently used recipe since appending a null byte won't work
if a null byte may be part of the data. Here is an example where both
techniques are used: after two null terminated strings with source and
destination address, a Short Message (to a mobile phone) is sent after
a length byte:</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">$msg</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;Z*Z*CA*&#39;</span><span class="cm">,</span> <span class="i">$src</span><span class="cm">,</span> <span class="i">$dst</span><span class="cm">,</span> <a class="l_k" href="functions/length.html">length</a><span class="s">(</span> <span class="i">$sm</span> <span class="s">)</span><span class="cm">,</span> <span class="i">$sm</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Unpacking this message can be done with the same template:</p>
<pre class="verbatim"><ol><li>   <span class="s">(</span> <span class="i">$src</span><span class="cm">,</span> <span class="i">$dst</span><span class="cm">,</span> <span class="i">$len</span><span class="cm">,</span> <span class="i">$sm</span> <span class="s">)</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;Z*Z*CA*&#39;</span><span class="cm">,</span> <span class="i">$msg</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>There's a subtle trap lurking in the offing: Adding another field after
the Short Message (in variable <code class="inline"><span class="i">$sm</span></code>
) is all right when packing, but this
cannot be unpacked naively:</p>
<pre class="verbatim"><ol><li>   <span class="c"># pack a message</span></li><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">$msg</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;Z*Z*CA*C&#39;</span><span class="cm">,</span> <span class="i">$src</span><span class="cm">,</span> <span class="i">$dst</span><span class="cm">,</span> <a class="l_k" href="functions/length.html">length</a><span class="s">(</span> <span class="i">$sm</span> <span class="s">)</span><span class="cm">,</span> <span class="i">$sm</span><span class="cm">,</span> <span class="i">$prio</span> <span class="s">)</span><span class="sc">;</span></li><li></li><li>   <span class="c"># unpack fails - $prio remains undefined!</span></li><li>   <span class="s">(</span> <span class="i">$src</span><span class="cm">,</span> <span class="i">$dst</span><span class="cm">,</span> <span class="i">$len</span><span class="cm">,</span> <span class="i">$sm</span><span class="cm">,</span> <span class="i">$prio</span> <span class="s">)</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;Z*Z*CA*C&#39;</span><span class="cm">,</span> <span class="i">$msg</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>The pack code <code class="inline"><span class="w">A</span>*</code>
 gobbles up all remaining bytes, and <code class="inline"><span class="i">$prio</span></code>
 remains
undefined! Before we let disappointment dampen the morale: Perl's got
the trump card to make this trick too, just a little further up the sleeve.
Watch this:</p>
<pre class="verbatim"><ol><li>   <span class="c"># pack a message: ASCIIZ, ASCIIZ, length/string, byte</span></li><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">$msg</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;Z* Z* C/A* C&#39;</span><span class="cm">,</span> <span class="i">$src</span><span class="cm">,</span> <span class="i">$dst</span><span class="cm">,</span> <span class="i">$sm</span><span class="cm">,</span> <span class="i">$prio</span> <span class="s">)</span><span class="sc">;</span></li><li></li><li>   <span class="c"># unpack</span></li><li>   <span class="s">(</span> <span class="i">$src</span><span class="cm">,</span> <span class="i">$dst</span><span class="cm">,</span> <span class="i">$sm</span><span class="cm">,</span> <span class="i">$prio</span> <span class="s">)</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;Z* Z* C/A* C&#39;</span><span class="cm">,</span> <span class="i">$msg</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Combining two pack codes with a slash (<code class="inline">/</code>) associates them with a single
value from the argument list. In <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code>, the length of the argument is
taken and packed according to the first code while the argument itself
is added after being converted with the template code after the slash.
This saves us the trouble of inserting the <code class="inline"><a class="l_k" href="functions/length.html">length</a></code> call, but it is 
in <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> where we really score: The value of the length byte marks the
end of the string to be taken from the buffer. Since this combination
doesn't make sense except when the second pack code isn't <code class="inline"><span class="w">a</span>*</code>
, <code class="inline"><span class="w">A</span>*</code>

or <code class="inline"><span class="w">Z</span>*</code>
, Perl won't let you.</p>
<p>The pack code preceding <code class="inline">/</code> may be anything that's fit to represent a
number: All the numeric binary pack codes, and even text codes such as
<code class="inline"><span class="w">A4</span></code>
 or <code class="inline"><span class="w">Z</span>*</code>
:</p>
<pre class="verbatim"><ol><li>   <span class="c"># pack/unpack a string preceded by its length in ASCII</span></li><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">$buf</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;A4/A*&#39;</span><span class="cm">,</span> <span class="q">&quot;Humpty-Dumpty&quot;</span> <span class="s">)</span><span class="sc">;</span></li><li>   <span class="c"># unpack $buf: &#39;13  Humpty-Dumpty&#39;</span></li><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">$txt</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;A4/A*&#39;</span><span class="cm">,</span> <span class="i">$buf</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p><code class="inline">/</code> is not implemented in Perls before 5.6, so if your code is required to
work on older Perls you'll need to <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;Z* Z* C&#39;</span><span class="s">)</span></code>
 to get the length,
then use it to make a new unpack string. For example</p>
<pre class="verbatim"><ol><li>   <span class="c"># pack a message: ASCIIZ, ASCIIZ, length, string, byte (5.005 compatible)</span></li><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">$msg</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;Z* Z* C A* C&#39;</span><span class="cm">,</span> <span class="i">$src</span><span class="cm">,</span> <span class="i">$dst</span><span class="cm">,</span> <a class="l_k" href="functions/length.html">length</a> <span class="i">$sm</span><span class="cm">,</span> <span class="i">$sm</span><span class="cm">,</span> <span class="i">$prio</span> <span class="s">)</span><span class="sc">;</span></li><li></li><li>   <span class="c"># unpack</span></li><li>   <span class="s">(</span> <a class="l_k" href="functions/undef.html">undef</a><span class="cm">,</span> <a class="l_k" href="functions/undef.html">undef</a><span class="cm">,</span> <span class="i">$len</span><span class="s">)</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;Z* Z* C&#39;</span><span class="cm">,</span> <span class="i">$msg</span> <span class="s">)</span><span class="sc">;</span></li><li>   <span class="s">(</span><span class="i">$src</span><span class="cm">,</span> <span class="i">$dst</span><span class="cm">,</span> <span class="i">$sm</span><span class="cm">,</span> <span class="i">$prio</span><span class="s">)</span> = <a class="l_k" href="functions/unpack.html">unpack</a> <span class="s">(</span> <span class="q">&quot;Z* Z* x A$len C&quot;</span><span class="cm">,</span> <span class="i">$msg</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>But that second <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> is rushing ahead. It isn't using a simple literal
string for the template. So maybe we should introduce...</p>
<a name="Dynamic-Templates"></a><h2>Dynamic Templates</h2>
<p>So far, we've seen literals used as templates. If the list of pack
items doesn't have fixed length, an expression constructing the
template is required (whenever, for some reason, <code class="inline"><span class="s">(</span><span class="s">)</span>*</code>
 cannot be used).
Here's an example: To store named string values in a way that can be
conveniently parsed by a C program, we create a sequence of names and
null terminated ASCII strings, with <code class="inline">=</code>
 between the name and the value,
followed by an additional delimiting null byte. Here's how:</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">$env</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;(A*A*Z*)&#39;</span> . <a class="l_k" href="functions/keys.html">keys</a><span class="s">(</span> <span class="i">%Env</span> <span class="s">)</span> . <span class="q">&#39;C&#39;</span><span class="cm">,</span></li><li>                   <a class="l_k" href="functions/map.html">map</a><span class="s">(</span> <span class="s">{</span> <span class="s">(</span> <span class="i">$_</span><span class="cm">,</span> <span class="q">&#39;=&#39;</span><span class="cm">,</span> <span class="i">$Env</span>{<span class="i">$_</span>} <span class="s">)</span> <span class="s">}</span> <a class="l_k" href="functions/keys.html">keys</a><span class="s">(</span> <span class="i">%Env</span> <span class="s">)</span> <span class="s">)</span><span class="cm">,</span> <span class="n">0</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Let's examine the cogs of this byte mill, one by one. There's the <code class="inline"><a class="l_k" href="functions/map.html">map</a></code>
call, creating the items we intend to stuff into the <code class="inline"><span class="i">$env</span></code>
 buffer:
to each key (in <code class="inline"><span class="i">$_</span></code>
) it adds the <code class="inline">=</code>
 separator and the hash entry value.
Each triplet is packed with the template code sequence <code class="inline"><span class="w">A</span>*<span class="w">A</span>*<span class="w">Z</span>*</code>
 that
is repeated according to the number of keys. (Yes, that's what the <code class="inline"><a class="l_k" href="functions/keys.html">keys</a></code>
function returns in scalar context.) To get the very last null byte,
we add a <code class="inline"><span class="n">0</span></code>
 at the end of the <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> list, to be packed with <code class="inline"><span class="w">C</span></code>
.
(Attentive readers may have noticed that we could have omitted the 0.)</p>
<p>For the reverse operation, we'll have to determine the number of items
in the buffer before we can let <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> rip it apart:</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">$n</span> = <span class="i">$env</span> =~ <span class="q">tr/\0//</span> - <span class="n">1</span><span class="sc">;</span></li><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">%env</span> = <a class="l_k" href="functions/map.html">map</a><span class="s">(</span> <a class="l_k" href="functions/split.html">split</a><span class="s">(</span> <span class="q">/=/</span><span class="cm">,</span> <span class="i">$_</span> <span class="s">)</span><span class="cm">,</span> <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&quot;(Z*)$n&quot;</span><span class="cm">,</span> <span class="i">$env</span> <span class="s">)</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>The <code class="inline"><a class="l_k" href="functions/tr.html">tr</a></code> counts the null bytes. The <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> call returns a list of
name-value pairs each of which is taken apart in the <code class="inline"><a class="l_k" href="functions/map.html">map</a></code> block.</p>
<a name="Counting-Repetitions"></a><h2>Counting Repetitions</h2>
<p>Rather than storing a sentinel at the end of a data item (or a list of items),
we could precede the data with a count. Again, we pack keys and values of
a hash, preceding each with an unsigned short length count, and up front
we store the number of pairs:</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">$env</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;S(S/A* S/A*)*&#39;</span><span class="cm">,</span> <a class="l_k" href="functions/scalar.html">scalar</a> <a class="l_k" href="functions/keys.html">keys</a><span class="s">(</span> <span class="i">%Env</span> <span class="s">)</span><span class="cm">,</span> <span class="i">%Env</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>This simplifies the reverse operation as the number of repetitions can be
unpacked with the <code class="inline">/</code> code:</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">%env</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;S/(S/A* S/A*)&#39;</span><span class="cm">,</span> <span class="i">$env</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Note that this is one of the rare cases where you cannot use the same
template for <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> and <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> because <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> can't determine
a repeat count for a <code class="inline"><span class="s">(</span><span class="s">)</span></code>
-group.</p>
<a name="Intel-HEX"></a><h2>Intel HEX</h2>
<p>Intel HEX is a file format for representing binary data, mostly for
programming various chips, as a text file. (See
<a href="http://en.wikipedia.org/wiki/.hex">http://en.wikipedia.org/wiki/.hex</a> for a detailed description, and
<a href="http://en.wikipedia.org/wiki/SREC_">http://en.wikipedia.org/wiki/SREC_</a>(file_format) for the Motorola
S-record format, which can be unravelled using the same technique.)
Each line begins with a colon (':') and is followed by a sequence of
hexadecimal characters, specifying a byte count <i>n</i> (8 bit),
an address (16 bit, big endian), a record type (8 bit), <i>n</i> data bytes
and a checksum (8 bit) computed as the least significant byte of the two's
complement sum of the preceding bytes. Example: <code class="inline">:0300300002337A1E</code>.</p>
<p>The first step of processing such a line is the conversion, to binary,
of the hexadecimal data, to obtain the four fields, while checking the
checksum. No surprise here: we'll start with a simple <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> call to 
convert everything to binary:</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">$binrec</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;H*&#39;</span><span class="cm">,</span> <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span> <span class="i">$hexrec</span><span class="cm">,</span> <span class="n">1</span> <span class="s">)</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>The resulting byte sequence is most convenient for checking the checksum.
Don't slow your program down with a for loop adding the <code class="inline"><a class="l_k" href="functions/ord.html">ord</a></code> values
of this string's bytes - the <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> code <code class="inline"><span class="i">%</span></code>
 is the thing to use
for computing the 8-bit sum of all bytes, which must be equal to zero:</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/die.html">die</a> unless <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&quot;%8C*&quot;</span><span class="cm">,</span> <span class="i">$binrec</span> <span class="s">)</span> == <span class="n">0</span><span class="sc">;</span></li></ol></pre><p>Finally, let's get those four fields. By now, you shouldn't have any
problems with the first three fields - but how can we use the byte count
of the data in the first field as a length for the data field? Here
the codes <code class="inline"><span class="w">x</span></code>
 and <code class="inline"><span class="w">X</span></code>
 come to the rescue, as they permit jumping
back and forth in the string to unpack.</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/my.html">my</a><span class="s">(</span> <span class="i">$addr</span><span class="cm">,</span> <span class="i">$type</span><span class="cm">,</span> <span class="i">$data</span> <span class="s">)</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&quot;x n C X4 C x3 /a&quot;</span><span class="cm">,</span> <span class="i">$bin</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Code <code class="inline"><span class="w">x</span></code>
 skips a byte, since we don't need the count yet. Code <code class="inline"><span class="w">n</span></code>
 takes
care of the 16-bit big-endian integer address, and <code class="inline"><span class="w">C</span></code>
 unpacks the
record type. Being at offset 4, where the data begins, we need the count.
<code class="inline"><span class="w">X4</span></code>
 brings us back to square one, which is the byte at offset 0.
Now we pick up the count, and zoom forth to offset 4, where we are
now fully furnished to extract the exact number of data bytes, leaving
the trailing checksum byte alone.</p>
<a name="Packing-and-Unpacking-C-Structures"></a><h1>Packing and Unpacking C Structures</h1>
<p>In previous sections we have seen how to pack numbers and character
strings. If it were not for a couple of snags we could conclude this
section right away with the terse remark that C structures don't
contain anything else, and therefore you already know all there is to it.
Sorry, no: read on, please.</p>
<p>If you have to deal with a lot of C structures, and don't want to
hack all your template strings manually, you'll probably want to have
a look at the CPAN module <code class="inline"><span class="w">Convert::Binary::C</span></code>
. Not only can it parse
your C source directly, but it also has built-in support for all the
odds and ends described further on in this section.</p>
<a name="The-Alignment-Pit"></a><h2>The Alignment Pit</h2>
<p>In the consideration of speed against memory requirements the balance
has been tilted in favor of faster execution. This has influenced the
way C compilers allocate memory for structures: On architectures
where a 16-bit or 32-bit operand can be moved faster between places in
memory, or to or from a CPU register, if it is aligned at an even or 
multiple-of-four or even at a multiple-of eight address, a C compiler
will give you this speed benefit by stuffing extra bytes into structures.
If you don't cross the C shoreline this is not likely to cause you any
grief (although you should care when you design large data structures,
or you want your code to be portable between architectures (you do want
that, don't you?)).</p>
<p>To see how this affects <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> and <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code>, we'll compare these two
C structures:</p>
<pre class="verbatim"><ol><li>   <span class="w">typedef</span> <span class="i">struct</span> <span class="s">{</span></li><li>     <span class="w">char</span>     <span class="w">c1</span><span class="sc">;</span></li><li>     <span class="w">short</span>    <span class="q">s;</span></li><li>     <span class="q">     char     c2;</span></li><li>     <span class="q">     long     l;</span></li><li>   <span class="s">}</span> <span class="w">gappy_t</span><span class="sc">;</span></li><li></li><li>   <span class="w">typedef</span> <span class="i">struct</span> <span class="s">{</span></li><li>     <span class="w">long</span>     <span class="w">l</span><span class="sc">;</span></li><li>     <span class="w">short</span>    <span class="q">s;</span></li><li>     <span class="q">     char     c1;</span></li><li>     <span class="q">     char     c2;</span></li><li>   <span class="s">}</span> <span class="w">dense_t</span><span class="sc">;</span></li></ol></pre><p>Typically, a C compiler allocates 12 bytes to a <code class="inline"><span class="w">gappy_t</span></code>
 variable, but
requires only 8 bytes for a <code class="inline"><span class="w">dense_t</span></code>
. After investigating this further,
we can draw memory maps, showing where the extra 4 bytes are hidden:</p>
<pre class="verbatim"><ol><li>   0           +4          +8          +12</li><li>   +--+--+--+--+--+--+--+--+--+--+--+--+</li><li>   |c1|xx|  s  |c2|xx|xx|xx|     l     |    xx = fill byte</li><li>   +--+--+--+--+--+--+--+--+--+--+--+--+</li><li>   gappy_t</li><li></li><li>   0           +4          +8</li><li>   +--+--+--+--+--+--+--+--+</li><li>   |     l     |  h  |c1|c2|</li><li>   +--+--+--+--+--+--+--+--+</li><li>   dense_t</li></ol></pre><p>And that's where the first quirk strikes: <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> and <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code>
templates have to be stuffed with <code class="inline"><span class="w">x</span></code>
 codes to get those extra fill bytes.</p>
<p>The natural question: "Why can't Perl compensate for the gaps?" warrants
an answer. One good reason is that C compilers might provide (non-ANSI)
extensions permitting all sorts of fancy control over the way structures
are aligned, even at the level of an individual structure field. And, if
this were not enough, there is an insidious thing called <code class="inline"><span class="w">union</span></code>
 where
the amount of fill bytes cannot be derived from the alignment of the next
item alone.</p>
<p>OK, so let's bite the bullet. Here's one way to get the alignment right
by inserting template codes <code class="inline"><span class="w">x</span></code>
, which don't take a corresponding item 
from the list:</p>
<pre class="verbatim"><ol><li>  <a class="l_k" href="functions/my.html">my</a> <span class="i">$gappy</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;cxs cxxx l!&#39;</span><span class="cm">,</span> <span class="i">$c1</span><span class="cm">,</span> <span class="i">$s</span><span class="cm">,</span> <span class="i">$c2</span><span class="cm">,</span> <span class="i">$l</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Note the <code class="inline">!</code>
 after <code class="inline"><span class="w">l</span></code>
: We want to make sure that we pack a long
integer as it is compiled by our C compiler. And even now, it will only
work for the platforms where the compiler aligns things as above.
And somebody somewhere has a platform where it doesn't.
[Probably a Cray, where <code class="inline"><span class="w">short</span></code>
s, <code class="inline"><a class="l_k" href="functions/int.html">int</a></code>s and <code class="inline"><span class="w">long</span></code>
s are all 8 bytes. :-)]</p>
<p>Counting bytes and watching alignments in lengthy structures is bound to 
be a drag. Isn't there a way we can create the template with a simple
program? Here's a C program that does the trick:</p>
<pre class="verbatim"><ol><li>   #include &lt;stdio.h&gt;</li><li>   #include &lt;stddef.h&gt;</li><li></li><li>   typedef struct {</li><li>     char     fc1;</li><li>     short    fs;</li><li>     char     fc2;</li><li>     long     fl;</li><li>   } gappy_t;</li><li></li><li>   #define Pt(struct,field,tchar) \</li><li>     printf( "@%d%s ", offsetof(struct,field), # tchar );</li><li></li><li>   int main() {</li><li>     Pt( gappy_t, fc1, c  );</li><li>     Pt( gappy_t, fs,  s! );</li><li>     Pt( gappy_t, fc2, c  );</li><li>     Pt( gappy_t, fl,  l! );</li><li>     printf( "\n" );</li><li>   }</li></ol></pre><p>The output line can be used as a template in a <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> or <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> call:</p>
<pre class="verbatim"><ol><li>  <a class="l_k" href="functions/my.html">my</a> <span class="i">$gappy</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;@0c @2s! @4c @8l!&#39;</span><span class="cm">,</span> <span class="i">$c1</span><span class="cm">,</span> <span class="i">$s</span><span class="cm">,</span> <span class="i">$c2</span><span class="cm">,</span> <span class="i">$l</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Gee, yet another template code - as if we hadn't plenty. But 
<code class="inline"><span class="i">@</span></code>
 saves our day by enabling us to specify the offset from the beginning
of the pack buffer to the next item: This is just the value
the <code class="inline"><span class="w">offsetof</span></code>
 macro (defined in <code class="inline"><span class="q">&lt;stddef.h&gt;</span></code>
) returns when
given a <code class="inline"><span class="w">struct</span></code>
 type and one of its field names ("member-designator" in 
C standardese).</p>
<p>Neither using offsets nor adding <code class="inline"><span class="w">x</span></code>
's to bridge the gaps is satisfactory.
(Just imagine what happens if the structure changes.) What we really need
is a way of saying "skip as many bytes as required to the next multiple of N".
In fluent Templatese, you say this with <code class="inline"><span class="w">x</span>!<span class="w">N</span></code>
 where N is replaced by the
appropriate value. Here's the next version of our struct packaging:</p>
<pre class="verbatim"><ol><li>  <a class="l_k" href="functions/my.html">my</a> <span class="i">$gappy</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;c x!2 s c x!4 l!&#39;</span><span class="cm">,</span> <span class="i">$c1</span><span class="cm">,</span> <span class="i">$s</span><span class="cm">,</span> <span class="i">$c2</span><span class="cm">,</span> <span class="i">$l</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>That's certainly better, but we still have to know how long all the
integers are, and portability is far away. Rather than <code class="inline"><span class="n">2</span></code>
,
for instance, we want to say "however long a short is". But this can be
done by enclosing the appropriate pack code in brackets: <code class="inline">[s]</code>. So, here's
the very best we can do:</p>
<pre class="verbatim"><ol><li>  <a class="l_k" href="functions/my.html">my</a> <span class="i">$gappy</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;c x![s] s c x![l!] l!&#39;</span><span class="cm">,</span> <span class="i">$c1</span><span class="cm">,</span> <span class="i">$s</span><span class="cm">,</span> <span class="i">$c2</span><span class="cm">,</span> <span class="i">$l</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><a name="Dealing-with-Endian-ness"></a><h2>Dealing with Endian-ness</h2>
<p>Now, imagine that we want to pack the data for a machine with a
different byte-order. First, we'll have to figure out how big the data
types on the target machine really are. Let's assume that the longs are
32 bits wide and the shorts are 16 bits wide. You can then rewrite the
template as:</p>
<pre class="verbatim"><ol><li>  <a class="l_k" href="functions/my.html">my</a> <span class="i">$gappy</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">'c x![s] s c x![l] l'</span><span class="cm">,</span> <span class="i">$c1</span><span class="cm">,</span> <span class="i">$s</span><span class="cm">,</span> <span class="i">$c2</span><span class="cm">,</span> <span class="i">$l</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>If the target machine is little-endian, we could write:</p>
<pre class="verbatim"><ol><li>  <a class="l_k" href="functions/my.html">my</a> <span class="i">$gappy</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">'c x![s] s&lt; c x![l] l&lt;'</span><span class="cm">,</span> <span class="i">$c1</span><span class="cm">,</span> <span class="i">$s</span><span class="cm">,</span> <span class="i">$c2</span><span class="cm">,</span> <span class="i">$l</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>This forces the short and the long members to be little-endian, and is
just fine if you don't have too many struct members. But we could also
use the byte-order modifier on a group and write the following:</p>
<pre class="verbatim"><ol><li>  <a class="l_k" href="functions/my.html">my</a> <span class="i">$gappy</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">'( c x![s] s c x![l] l )&lt;'</span><span class="cm">,</span> <span class="i">$c1</span><span class="cm">,</span> <span class="i">$s</span><span class="cm">,</span> <span class="i">$c2</span><span class="cm">,</span> <span class="i">$l</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>This is not as short as before, but it makes it more obvious that we
intend to have little-endian byte-order for a whole group, not only
for individual template codes. It can also be more readable and easier
to maintain.</p>
<a name="Alignment%2c-Take-2"></a><h2>Alignment, Take 2</h2>
<p>I'm afraid that we're not quite through with the alignment catch yet. The
hydra raises another ugly head when you pack arrays of structures:</p>
<pre class="verbatim"><ol><li>   <span class="w">typedef</span> <span class="i">struct</span> <span class="s">{</span></li><li>     <span class="w">short</span>    <span class="w">count</span><span class="sc">;</span></li><li>     <span class="w">char</span>     <span class="w">glyph</span><span class="sc">;</span></li><li>   <span class="s">}</span> <span class="w">cell_t</span><span class="sc">;</span></li><li></li><li>   <span class="w">typedef</span> <span class="w">cell_t</span> <span class="w">buffer_t</span><span class="s">[</span><span class="w">BUFLEN</span><span class="s">]</span><span class="sc">;</span></li></ol></pre><p>Where's the catch? Padding is neither required before the first field <code class="inline"><span class="w">count</span></code>
,
nor between this and the next field <code class="inline"><span class="w">glyph</span></code>
, so why can't we simply pack
like this:</p>
<pre class="verbatim"><ol><li>   <span class="c"># something goes wrong here:</span></li><li>   <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;s!a&#39;</span> x <span class="i">@buffer</span><span class="cm">,</span></li><li>         <a class="l_k" href="functions/map.html">map</a><span class="s">{</span> <span class="s">(</span> <span class="i">$_</span>-&gt;{<span class="w">count</span>}<span class="cm">,</span> <span class="i">$_</span>-&gt;{<span class="w">glyph</span>} <span class="s">)</span> <span class="s">}</span> <span class="i">@buffer</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>This packs <code class="inline"><span class="n">3</span>*<span class="i">@buffer</span></code>
 bytes, but it turns out that the size of 
<code class="inline"><span class="w">buffer_t</span></code>
 is four times <code class="inline"><span class="w">BUFLEN</span></code>
! The moral of the story is that
the required alignment of a structure or array is propagated to the
next higher level where we have to consider padding <i>at the end</i>
of each component as well. Thus the correct template is:</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;s!ax&#39;</span> x <span class="i">@buffer</span><span class="cm">,</span></li><li>         <a class="l_k" href="functions/map.html">map</a><span class="s">{</span> <span class="s">(</span> <span class="i">$_</span>-&gt;{<span class="w">count</span>}<span class="cm">,</span> <span class="i">$_</span>-&gt;{<span class="w">glyph</span>} <span class="s">)</span> <span class="s">}</span> <span class="i">@buffer</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><a name="Alignment%2c-Take-3"></a><h2>Alignment, Take 3</h2>
<p>And even if you take all the above into account, ANSI still lets this:</p>
<pre class="verbatim"><ol><li>   <span class="w">typedef</span> <span class="i">struct</span> <span class="s">{</span></li><li>     <span class="w">char</span>     <span class="w">foo</span><span class="s">[</span><span class="n">2</span><span class="s">]</span><span class="sc">;</span></li><li>   <span class="s">}</span> <span class="w">foo_t</span><span class="sc">;</span></li></ol></pre><p>vary in size. The alignment constraint of the structure can be greater than
any of its elements. [And if you think that this doesn't affect anything
common, dismember the next cellphone that you see. Many have ARM cores, and
the ARM structure rules make <code class="inline"><span class="w">sizeof</span> <span class="s">(</span><span class="w">foo_t</span><span class="s">)</span></code>
 == 4]</p>
<a name="Pointers-for-How-to-Use-Them"></a><h2>Pointers for How to Use Them</h2>
<p>The title of this section indicates the second problem you may run into
sooner or later when you pack C structures. If the function you intend
to call expects a, say, <code class="inline"><span class="w">void</span> *</code>
 value, you <i>cannot</i> simply take
a reference to a Perl variable. (Although that value certainly is a
memory address, it's not the address where the variable's contents are
stored.)</p>
<p>Template code <code class="inline"><span class="w">P</span></code>
 promises to pack a "pointer to a fixed length string".
Isn't this what we want? Let's try:</p>
<pre class="verbatim"><ol><li>    <span class="c"># allocate some storage and pack a pointer to it</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$memory</span> = <span class="q">&quot;\x00&quot;</span> x <span class="i">$size</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$memptr</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;P&#39;</span><span class="cm">,</span> <span class="i">$memory</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>But wait: doesn't <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> just return a sequence of bytes? How can we pass this
string of bytes to some C code expecting a pointer which is, after all,
nothing but a number? The answer is simple: We have to obtain the numeric
address from the bytes returned by <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code>.</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$ptr</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;L!&#39;</span><span class="cm">,</span> <span class="i">$memptr</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Obviously this assumes that it is possible to typecast a pointer
to an unsigned long and vice versa, which frequently works but should not
be taken as a universal law. - Now that we have this pointer the next question
is: How can we put it to good use? We need a call to some C function
where a pointer is expected. The read(2) system call comes to mind:</p>
<pre class="verbatim"><ol><li>    <span class="w">ssize_t</span> <a class="l_k" href="functions/read.html">read</a><span class="s">(</span><a class="l_k" href="functions/int.html">int</a> <span class="w">fd</span><span class="cm">,</span> <span class="w">void</span> *<span class="w">buf</span><span class="cm">,</span> <span class="w">size_t</span> <span class="w">count</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>After reading <a href="perlfunc.html">perlfunc</a> explaining how to use <code class="inline"><a class="l_k" href="functions/syscall.html">syscall</a></code> we can write
this Perl function copying a file to standard output:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/require.html">require</a> <span class="q">&#39;syscall.ph&#39;</span><span class="sc">;</span></li><li><a name="cat"></a>    sub <span class="m">cat($)</span><span class="s">{</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$path</span> = <a class="l_k" href="functions/shift.html">shift</a><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$size</span> = -s <span class="i">$path</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$memory</span> = <span class="q">&quot;\x00&quot;</span> x <span class="i">$size</span><span class="sc">;</span>  <span class="c"># allocate some memory</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$ptr</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;L&#39;</span><span class="cm">,</span> <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;P&#39;</span><span class="cm">,</span> <span class="i">$memory</span> <span class="s">)</span> <span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/open.html">open</a><span class="s">(</span> <span class="w">F</span><span class="cm">,</span> <span class="i">$path</span> <span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a><span class="s">(</span> <span class="q">&quot;$path: cannot open ($!)\n&quot;</span> <span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$fd</span> = <a class="l_k" href="functions/fileno.html">fileno</a><span class="s">(</span><span class="w">F</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$res</span> = <a class="l_k" href="functions/syscall.html">syscall</a><span class="s">(</span> <span class="i">&amp;SYS_read</span><span class="cm">,</span> <a class="l_k" href="functions/fileno.html">fileno</a><span class="s">(</span><span class="w">F</span><span class="s">)</span><span class="cm">,</span> <span class="i">$ptr</span><span class="cm">,</span> <span class="i">$size</span> <span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="i">$memory</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/close.html">close</a><span class="s">(</span> <span class="w">F</span> <span class="s">)</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>This is neither a specimen of simplicity nor a paragon of portability but
it illustrates the point: We are able to sneak behind the scenes and
access Perl's otherwise well-guarded memory! (Important note: Perl's
<code class="inline"><a class="l_k" href="functions/syscall.html">syscall</a></code> does <i>not</i> require you to construct pointers in this roundabout
way. You simply pass a string variable, and Perl forwards the address.)</p>
<p>How does <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> with <code class="inline"><span class="w">P</span></code>
 work? Imagine some pointer in the buffer
about to be unpacked: If it isn't the null pointer (which will smartly
produce the <code class="inline"><a class="l_k" href="functions/undef.html">undef</a></code> value) we have a start address - but then what?
Perl has no way of knowing how long this "fixed length string" is, so
it's up to you to specify the actual size as an explicit length after <code class="inline"><span class="w">P</span></code>
.</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">$mem</span> = <span class="q">&quot;abcdefghijklmn&quot;</span><span class="sc">;</span></li><li>   <a class="l_k" href="functions/print.html">print</a> <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;P5&#39;</span><span class="cm">,</span> <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;P&#39;</span><span class="cm">,</span> <span class="i">$mem</span> <span class="s">)</span> <span class="s">)</span><span class="sc">;</span> <span class="c"># prints &quot;abcde&quot;</span></li></ol></pre><p>As a consequence, <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> ignores any number or <code class="inline"><span class="i">*</span></code>
 after <code class="inline"><span class="w">P</span></code>
.</p>
<p>Now that we have seen <code class="inline"><span class="w">P</span></code>
 at work, we might as well give <code class="inline"><span class="w">p</span></code>
 a whirl.
Why do we need a second template code for packing pointers at all? The 
answer lies behind the simple fact that an <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> with <code class="inline"><span class="w">p</span></code>
 promises
a null-terminated string starting at the address taken from the buffer,
and that implies a length for the data item to be returned:</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/my.html">my</a> <span class="i">$buf</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;p&#39;</span><span class="cm">,</span> <span class="q">&quot;abc\x00efhijklmn&quot;</span> <span class="s">)</span><span class="sc">;</span></li><li>   <a class="l_k" href="functions/print.html">print</a> <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;p&#39;</span><span class="cm">,</span> <span class="i">$buf</span> <span class="s">)</span><span class="sc">;</span>    <span class="c"># prints &quot;abc&quot;</span></li></ol></pre><p>Albeit this is apt to be confusing: As a consequence of the length being
implied by the string's length, a number after pack code <code class="inline"><span class="w">p</span></code>
 is a repeat
count, not a length as after <code class="inline"><span class="w">P</span></code>
.</p>
<p>Using <code class="inline"><a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span>...<span class="cm">,</span> <span class="i">$x</span><span class="s">)</span></code>
 with <code class="inline"><span class="w">P</span></code>
 or <code class="inline"><span class="w">p</span></code>
 to get the address where <code class="inline"><span class="i">$x</span></code>
 is
actually stored must be used with circumspection. Perl's internal machinery
considers the relation between a variable and that address as its very own 
private matter and doesn't really care that we have obtained a copy. Therefore:</p>
<ul>
<li>
<p>Do not use <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> with <code class="inline"><span class="w">p</span></code>
 or <code class="inline"><span class="w">P</span></code>
 to obtain the address of variable
that's bound to go out of scope (and thereby freeing its memory) before you
are done with using the memory at that address.</p>
</li>
<li>
<p>Be very careful with Perl operations that change the value of the
variable. Appending something to the variable, for instance, might require
reallocation of its storage, leaving you with a pointer into no-man's land.</p>
</li>
<li>
<p>Don't think that you can get the address of a Perl variable
when it is stored as an integer or double number! <code class="inline"><a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span><span class="q">&#39;P&#39;</span><span class="cm">,</span> <span class="i">$x</span><span class="s">)</span></code>
 will
force the variable's internal representation to string, just as if you
had written something like <code class="inline"><span class="i">$x</span> .= <span class="q">&#39;&#39;</span></code>
.</p>
</li>
</ul>
<p>It's safe, however, to P- or p-pack a string literal, because Perl simply
allocates an anonymous variable.</p>
<a name="Pack-Recipes"></a><h1>Pack Recipes</h1>
<p>Here are a collection of (possibly) useful canned recipes for <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code>
and <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code>:</p>
<pre class="verbatim"><ol><li>    <span class="c"># Convert IP address for socket functions</span></li><li>    <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&quot;C4&quot;</span><span class="cm">,</span> <a class="l_k" href="functions/split.html">split</a> <span class="q">/\./</span><span class="cm">,</span> <span class="q">&quot;123.4.5.6&quot;</span> <span class="s">)</span><span class="sc">;</span> </li><li></li><li>    <span class="c"># Count the bits in a chunk of memory (e.g. a select vector)</span></li><li>    <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;%32b*&#39;</span><span class="cm">,</span> <span class="i">$mask</span> <span class="s">)</span><span class="sc">;</span></li><li></li><li>    <span class="c"># Determine the endianness of your system</span></li><li>    <span class="i">$is_little_endian</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;c&#39;</span><span class="cm">,</span> <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;s&#39;</span><span class="cm">,</span> <span class="n">1</span> <span class="s">)</span> <span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$is_big_endian</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;xc&#39;</span><span class="cm">,</span> <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;s&#39;</span><span class="cm">,</span> <span class="n">1</span> <span class="s">)</span> <span class="s">)</span><span class="sc">;</span></li><li></li><li>    <span class="c"># Determine the number of bits in a native integer</span></li><li>    <span class="i">$bits</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;%32I!&#39;</span><span class="cm">,</span> ~<span class="n">0</span> <span class="s">)</span><span class="sc">;</span></li><li></li><li>    <span class="c"># Prepare argument for the nanosleep system call</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$timespec</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;L!L!&#39;</span><span class="cm">,</span> <span class="i">$secs</span><span class="cm">,</span> <span class="i">$nanosecs</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>For a simple memory dump we unpack some bytes into just as 
many pairs of hex digits, and use <code class="inline"><a class="l_k" href="functions/map.html">map</a></code> to handle the traditional
spacing - 16 bytes to a line:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$i</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/print.html">print</a> <a class="l_k" href="functions/map.html">map</a><span class="s">(</span> ++<span class="i">$i</span> % <span class="n">16</span> ? <span class="q">&quot;$_ &quot;</span> <span class="co">:</span> <span class="q">&quot;$_\n&quot;</span><span class="cm">,</span></li><li>               <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;H2&#39;</span> x <a class="l_k" href="functions/length.html">length</a><span class="s">(</span> <span class="i">$mem</span> <span class="s">)</span><span class="cm">,</span> <span class="i">$mem</span> <span class="s">)</span> <span class="s">)</span><span class="cm">,</span></li><li>          <a class="l_k" href="functions/length.html">length</a><span class="s">(</span> <span class="i">$mem</span> <span class="s">)</span> % <span class="n">16</span> ? <span class="q">&quot;\n&quot;</span> <span class="co">:</span> <span class="q">&#39;&#39;</span><span class="sc">;</span></li></ol></pre><a name="Funnies-Section"></a><h1>Funnies Section</h1>
<pre class="verbatim"><ol><li>    <span class="c"># Pulling digits out of nowhere...</span></li><li>    <a class="l_k" href="functions/print.html">print</a> <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;C&#39;</span><span class="cm">,</span> <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;x&#39;</span> <span class="s">)</span> <span class="s">)</span><span class="cm">,</span></li><li>          <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;%B*&#39;</span><span class="cm">,</span> <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;A&#39;</span> <span class="s">)</span> <span class="s">)</span><span class="cm">,</span></li><li>          <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;H&#39;</span><span class="cm">,</span> <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;A&#39;</span> <span class="s">)</span> <span class="s">)</span><span class="cm">,</span></li><li>          <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;A&#39;</span><span class="cm">,</span> <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="q">&#39;C&#39;</span><span class="cm">,</span> <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;A&#39;</span> <span class="s">)</span> <span class="s">)</span> <span class="s">)</span><span class="cm">,</span> <span class="q">&quot;\n&quot;</span><span class="sc">;</span></li><li></li><li>    <span class="c"># One for the road ;-)</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$advice</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span> <span class="q">&#39;all u can in a van&#39;</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><a name="Authors"></a><h1>Authors</h1>
<p>Simon Cozens and Wolfgang Laun.</p>




  <div id="page_index" class="hud_container">
    <div id="page_index_header" class="hud_header">
      <div id="page_index_close" class="hud_close"><a href="#" onClick="pageIndex.hide();return false;"></a></div>
      <div id="page_index_title" class="hud_title"><span class="hud_span_top">Page index</span></div>
      <div id="page_index_topright" class="hud_topright"></div>
    </div>
    <div id="page_index_content" class="hud_content">
      <ul><li><a href="#NAME">NAME</a><li><a href="#DESCRIPTION">DESCRIPTION</a><li><a href="#The-Basic-Principle">The Basic Principle</a><li><a href="#Packing-Text">Packing Text</a><li><a href="#Packing-Numbers">Packing Numbers</a><ul><li><a href="#Integers">Integers</a><li><a href="#Unpacking-a-Stack-Frame">Unpacking a Stack Frame</a><li><a href="#How-to-Eat-an-Egg-on-a-Net">How to Eat an Egg on a Net</a><li><a href="#Byte-order-modifiers">Byte-order modifiers</a><li><a href="#Floating-point-Numbers">Floating point Numbers</a></ul><li><a href="#Exotic-Templates">Exotic Templates</a><ul><li><a href="#Bit-Strings">Bit Strings</a><li><a href="#Uuencoding">Uuencoding</a><li><a href="#Doing-Sums">Doing Sums</a><li><a href="#Unicode">Unicode</a><li><a href="#Another-Portable-Binary-Encoding">Another Portable Binary Encoding</a></ul><li><a href="#Template-Grouping">Template Grouping</a><li><a href="#Lengths-and-Widths">Lengths and Widths</a><ul><li><a href="#String-Lengths">String Lengths</a><li><a href="#Dynamic-Templates">Dynamic Templates</a><li><a href="#Counting-Repetitions">Counting Repetitions</a><li><a href="#Intel-HEX">Intel HEX</a></ul><li><a href="#Packing-and-Unpacking-C-Structures">Packing and Unpacking C Structures</a><ul><li><a href="#The-Alignment-Pit">The Alignment Pit</a><li><a href="#Dealing-with-Endian-ness">Dealing with Endian-ness</a><li><a href="#Alignment%2c-Take-2">Alignment, Take 2</a><li><a href="#Alignment%2c-Take-3">Alignment, Take 3</a><li><a href="#Pointers-for-How-to-Use-Them">Pointers for How to Use Them</a></ul><li><a href="#Pack-Recipes">Pack Recipes</a><li><a href="#Funnies-Section">Funnies Section</a><li><a href="#Authors">Authors</a></ul>
    </div>
    <div id="page_index_footer" class="hud_footer">
      <div id="page_index_bottomleft" class="hud_bottomleft"></div>
      <div id="page_index_bottom" class="hud_bottom"><span class="hud_span_bottom"></span></div>
      <div id="page_index_resize" class="hud_resize"></div>
    </div>
  </div>


	    &nbsp;
          </div>
          <div id="content_footer">
          </div>
        </div>
        <div class="clear"></div>
      </div>
      
    <div id="footer">
      <div id="footer_content">
        <div id="footer_strapline">
          perldoc.perl.org - Official documentation for the Perl programming language
        </div>
        <div id="footer_links">
          <div id="address">
            <p class="name">Contact details</p>
            <p class="address">
	      Site maintained by <a href="mailto:jj@jonallen.info">Jon Allen (JJ)</a><br>
	    </p>
            <p class="contact">
              Documentation maintained by the <a href="http://lists.cpan.org/showlist.cgi?name=perl5-porters">Perl 5 Porters</a>
            </p>
          </div>
          <ul class="f1">
            <li>Manual
              <ul class="f2">
                <li><a href="index-overview.html">Overview</a>
                <li><a href="index-tutorials.html">Tutorials</a>
                <li><a href="index-faq.html">FAQs</a>
                <li><a href="index-history.html">Changes</a>
              </ul>
            <li>Reference
              <ul class="f2">
                <li><a href="index-language.html">Language</a>
                <li><a href="index-functions.html">Functions</a>
                <li><a href="perlop.html">Operators</a>
                <li><a href="perlvar.html">Variables</a>
              </ul>
            <li>Modules
              <ul class="f2">
                <li><a href="index-modules-A.html">Modules</a>
                <li><a href="index-pragmas.html">Pragmas</a>
                <li><a href="index-utilities.html">Utilities</a>
              </ul>
            <li>Misc
              <ul class="f2">
                <li><a href="index-licence.html">License</a>
                <li><a href="index-internals.html">Internals</a>
                <li><a href="index-platforms.html">Platforms</a>
              </ul>          </ul>
          <div class="clear"></div>
        </div>
      </div>
      <div id="footer_end">
      </div>
    </div>
      
    </div>
      <script language="JavaScript" type="text/javascript" src="static/exploreperl.js"></script>
      <script language="JavaScript" src="static/combined-20100403.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
  perldoc.setPath(0);
  perldoc.pageName    = 'perlpacktut';
  perldoc.pageAddress = 'perlpacktut.html';
  perldoc.contentPage = 1;
  explorePerl.render();
  explorePerl.addEvents('explore_anchor');
</script>
    
  </body>
</html>