{
    "mode": "man",
    "parameter": "perlpacktut",
    "section": "1",
    "url": "https://www.chedong.com/phpMan.php/man/perlpacktut/1/json",
    "generated": "2026-10-22T12:06:29Z",
    "sections": {
        "NAME": {
            "content": "perlpacktut - tutorial on \"pack\" and \"unpack\"\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "\"pack\" and \"unpack\" are two functions for transforming data according to a user-defined\ntemplate, between the guarded way Perl stores values and some well-defined representation as\nmight be required in the environment of a Perl program. Unfortunately, they're also two of\nthe most misunderstood and most often overlooked functions that Perl provides. This tutorial\nwill demystify them for you.\n",
            "subsections": []
        },
        "The Basic Principle": {
            "content": "Most programming languages don't shelter the memory where variables are stored. In C, for\ninstance, you can take the address of some variable, and the \"sizeof\" operator tells you how\nmany bytes are allocated to the variable. Using the address and the size, you may access the\nstorage to your heart's content.\n\nIn Perl, you just can't access memory at random, but the structural and representational\nconversion provided by \"pack\" and \"unpack\" is an excellent alternative. The \"pack\" function\nconverts values to a byte sequence containing representations according to a given\nspecification, the so-called \"template\" argument. \"unpack\" is the reverse process, deriving\nsome values from the contents of a string of bytes. (Be cautioned, however, that not all that\nhas been packed together can be neatly unpacked - a very common experience as seasoned\ntravellers are likely to confirm.)\n\nWhy, you may ask, would you need a chunk of memory containing some values in binary\nrepresentation? One good reason is input and output accessing some file, a device, or a\nnetwork connection, whereby this binary representation is either forced on you or will give\nyou some benefit in processing. Another cause is passing data to some system call that is not\navailable as a Perl function: \"syscall\" requires you to provide parameters stored in the way\nit happens in a C program. Even text processing (as shown in the next section) may be\nsimplified with judicious usage of these two functions.\n\nTo see how (un)packing works, we'll start with a simple template code where the conversion is\nin low gear: between the contents of a byte sequence and a string of hexadecimal digits.\nLet's use \"unpack\", since this is likely to remind you of a dump program, or some desperate\nlast message unfortunate programs are wont to throw at you before they expire into the wild\nblue yonder. Assuming that the variable $mem holds a sequence of bytes that we'd like to\ninspect without assuming anything about its meaning, we can write\n\nmy( $hex ) = unpack( 'H*', $mem );\nprint \"$hex\\n\";\n\nwhereupon we might see something like this, with each pair of hex digits corresponding to a\nbyte:\n\n41204d414e204120504c414e20412043414e414c2050414e414d41\n\nWhat was in this chunk of memory? Numbers, characters, or a mixture of both? Assuming that\nwe're on a computer where ASCII (or some similar) encoding is used: hexadecimal values in the\nrange 0x40 - 0x5A indicate an uppercase letter, and 0x20 encodes a space. So we might assume\nit is a piece of text, which some are able to read like a tabloid; but others will have to\nget hold of an ASCII table and relive that firstgrader feeling. Not caring too much about\nwhich way to read this, we note that \"unpack\" with the template code \"H\" converts the\ncontents of a sequence of bytes into the customary hexadecimal notation. Since \"a sequence\nof\" is a pretty vague indication of quantity, \"H\" has been defined to convert just a single\nhexadecimal digit unless it is followed by a repeat count. An asterisk for the repeat count\nmeans to use whatever remains.\n\nThe inverse operation - packing byte contents from a string of hexadecimal digits - is just\nas easily written. For instance:\n\nmy $s = pack( 'H2' x 10, 30..39 );\nprint \"$s\\n\";\n\nSince we feed a list of ten 2-digit hexadecimal strings to \"pack\", the pack template should\ncontain ten pack codes. If this is run on a computer with ASCII character coding, it will\nprint 0123456789.\n",
            "subsections": []
        },
        "Packing Text": {
            "content": "Let's suppose you've got to read in a data file like this:\n\nDate      |Description                | Income|Expenditure\n01/24/2001 Zed's Camel Emporium                    1147.99\n01/28/2001 Flea spray                                24.99\n01/29/2001 Camel rides to tourists      235.00\n\nHow do we do it? You might think first to use \"split\"; however, since \"split\" collapses blank\nfields, you'll never know whether a record was income or expenditure. Oops. Well, you could\nalways use \"substr\":\n\nwhile (<>) {\nmy $date   = substr($,  0, 11);\nmy $desc   = substr($, 12, 27);\nmy $income = substr($, 40,  7);\nmy $expend = substr($, 52,  7);\n...\n}\n\nIt's not really a barrel of laughs, is it? In fact, it's worse than it may seem; the eagle-\neyed may notice that the first field should only be 10 characters wide, and the error has\npropagated right through the other numbers - which we've had to count by hand. So it's error-\nprone as well as horribly unfriendly.\n\nOr maybe we could use regular expressions:\n\nwhile (<>) {\nmy($date, $desc, $income, $expend) =\nm|(\\d\\d/\\d\\d/\\d{4}) (.{27}) (.{7})(.*)|;\n...\n}\n\nUrgh. Well, it's a bit better, but - well, would you want to maintain that?\n\nHey, isn't Perl supposed to make this sort of thing easy? Well, it does, if you use the right\ntools. \"pack\" and \"unpack\" are designed to help you out when dealing with fixed-width data\nlike the above. Let's have a look at a solution with \"unpack\":\n\nwhile (<>) {\nmy($date, $desc, $income, $expend) = unpack(\"A10xA27xA7A*\", $);\n...\n}\n\nThat looks a bit nicer; but we've got to take apart that weird template.  Where did I pull\nthat out of?\n\nOK, let's have a look at some of our data again; in fact, we'll include the headers, and a\nhandy ruler so we can keep track of where we are.\n\n1         2         3         4         5\n1234567890123456789012345678901234567890123456789012345678\nDate      |Description                | Income|Expenditure\n01/28/2001 Flea spray                                24.99\n01/29/2001 Camel rides to tourists      235.00\n\nFrom this, we can see that the date column stretches from column 1 to column 10 - ten\ncharacters wide. The \"pack\"-ese for \"character\" is \"A\", and ten of them are \"A10\". So if we\njust wanted to extract the dates, we could say this:\n\nmy($date) = unpack(\"A10\", $);\n\nOK, what's next? Between the date and the description is a blank column; we want to skip over\nthat. The \"x\" template means \"skip forward\", so we want one of those. Next, we have another\nbatch of characters, from 12 to 38. That's 27 more characters, hence \"A27\". (Don't make the\nfencepost error - there are 27 characters between 12 and 38, not 26. Count 'em!)\n\nNow we skip another character and pick up the next 7 characters:\n\nmy($date,$description,$income) = unpack(\"A10xA27xA7\", $);\n\nNow comes the clever bit. Lines in our ledger which are just income and not expenditure might\nend at column 46. Hence, we don't want to tell our \"unpack\" pattern that we need to find\nanother 12 characters; we'll just say \"if there's anything left, take it\". As you might guess\nfrom regular expressions, that's what the \"*\" means: \"use everything remaining\".\n\n•  Be warned, though, that unlike regular expressions, if the \"unpack\" template doesn't match\nthe incoming data, Perl will scream and die.\n\nHence, putting it all together:\n\nmy ($date, $description, $income, $expend) =\nunpack(\"A10xA27xA7xA*\", $);\n\nNow,  that's  our  data parsed. I suppose what we might want to do now is total up our income\nand expenditure, and add another line to the end of our ledger - in the same format -  saying\nhow much we've brought in and how much we've spent:\n\nwhile (<>) {\nmy ($date, $desc, $income, $expend) =\nunpack(\"A10xA27xA7xA*\", $);\n$totincome += $income;\n$totexpend += $expend;\n}\n\n$totincome = sprintf(\"%.2f\", $totincome); # Get them into\n$totexpend = sprintf(\"%.2f\", $totexpend); # \"financial\" format\n\n$date = POSIX::strftime(\"%m/%d/%Y\", localtime);\n\n# OK, let's go:\n\nprint pack(\"A10xA27xA7xA*\", $date, \"Totals\",\n$totincome, $totexpend);\n\nOh, hmm. That didn't quite work. Let's see what happened:\n\n01/24/2001 Zed's Camel Emporium                     1147.99\n01/28/2001 Flea spray                                 24.99\n01/29/2001 Camel rides to tourists     1235.00\n03/23/2001Totals                     1235.001172.98\n\nOK,  it's  a start, but what happened to the spaces? We put \"x\", didn't we? Shouldn't it skip\nforward? Let's look at what \"pack\" in perlfunc says:\n\nx   A null byte.\n\nUrgh. No wonder. There's a big difference between \"a  null  byte\",  character  zero,  and  \"a\nspace\",  character  32.  Perl's  put  something  between  the  date and the description - but\nunfortunately, we can't see it!\n\nWhat we actually need to do is expand the width of the fields. The \"A\" format pads  any  non-\nexistent  characters  with spaces, so we can use the additional spaces to line up our fields,\nlike this:\n\nprint pack(\"A11 A28 A8 A*\", $date, \"Totals\",\n$totincome, $totexpend);\n\n(Note that you can put spaces in the template to  make  it  more  readable,  but  they  don't\ntranslate to spaces in the output.) Here's what we got this time:\n\n01/24/2001 Zed's Camel Emporium                     1147.99\n01/28/2001 Flea spray                                 24.99\n01/29/2001 Camel rides to tourists     1235.00\n03/23/2001 Totals                      1235.00 1172.98\n\nThat's a bit better, but we still have that last column which needs to be moved further over.\nThere's  an  easy way to fix this up: unfortunately, we can't get \"pack\" to right-justify our\nfields, but we can get \"sprintf\" to do it:\n\n$totincome = sprintf(\"%.2f\", $totincome);\n$totexpend = sprintf(\"%12.2f\", $totexpend);\n$date = POSIX::strftime(\"%m/%d/%Y\", localtime);\nprint pack(\"A11 A28 A8 A*\", $date, \"Totals\",\n$totincome, $totexpend);\n\nThis time we get the right answer:\n\n01/28/2001 Flea spray                                 24.99\n01/29/2001 Camel rides to tourists     1235.00\n03/23/2001 Totals                      1235.00      1172.98\n\nSo that's how we consume and produce fixed-width data. Let's recap what we've seen of  \"pack\"\nand \"unpack\" so far:\n\n•  Use  \"pack\"  to go from several pieces of data to one fixed-width version; use \"unpack\" to\nturn a fixed-width-format string into several pieces of data.\n\n•  The pack format \"A\" means \"any character\"; if you're  \"pack\"ing  and  you've  run  out  of\nthings to pack, \"pack\" will fill the rest up with spaces.\n\n•  \"x\" means \"skip a byte\" when \"unpack\"ing; when \"pack\"ing, it means \"introduce a null byte\"\n- that's probably not what you mean if you're dealing with plain text.\n\n•  You  can  follow the formats with numbers to say how many characters should be affected by\nthat format: \"A12\" means \"take 12 characters\"; \"x6\" means \"skip 6 bytes\" or \"character  0,\n6 times\".\n\n•  Instead of a number, you can use \"*\" to mean \"consume everything else left\".\n\nWarning:  when packing multiple pieces of data, \"*\" only means \"consume all of the current\npiece of data\". That's to say\n\npack(\"A*A*\", $one, $two)\n\npacks all of $one into the first \"A*\" and then all of $two into  the  second.  This  is  a\ngeneral principle: each format character corresponds to one piece of data to be \"pack\"ed.\n",
            "subsections": []
        },
        "Packing Numbers": {
            "content": "So  much  for  textual data. Let's get onto the meaty stuff that \"pack\" and \"unpack\" are best\nat: handling binary formats for numbers. There is, of course, not just one binary  format   -\nlife would be too simple - but Perl will do all the finicky labor for you.\n",
            "subsections": [
                {
                    "name": "Integers",
                    "content": "Packing   and  unpacking  numbers  implies  conversion  to  and  from  some  specific  binary\nrepresentation. Leaving floating point numbers aside for the moment, the  salient  properties\nof any such representation are:\n\n•   the number of bytes used for storing the integer,\n\n•   whether the contents are interpreted as a signed or unsigned number,\n\n•   the  byte  ordering:  whether  the  first byte is the least or most significant byte (or:\nlittle-endian or big-endian, respectively).\n\nSo, for instance, to pack 20302 to a signed 16 bit integer in your computer's  representation\nyou write\n\nmy $ps = pack( 's', 20302 );\n\nAgain,  the  result  is a string, now containing 2 bytes. If you print this string (which is,\ngenerally, not recommended) you might see \"ON\" or  \"NO\"  (depending  on  your  system's  byte\nordering)  -  or  something  entirely  different if your computer doesn't use ASCII character\nencoding.  Unpacking $ps with the same template returns the original integer value:\n\nmy( $s ) = unpack( 's', $ps );\n\nThis is true for all numeric template codes. But don't expect miracles: if the  packed  value\nexceeds  the  allotted  byte  capacity,  high  order  bits are silently discarded, and unpack\ncertainly won't be able to pull them back out of some magic hat. And, when you pack  using  a\nsigned template code such as \"s\", an excess value may result in the sign bit getting set, and\nunpacking this will smartly return a negative value.\n\n16 bits won't get you too far with integers, but there is \"l\" and \"L\" for signed and unsigned\n32-bit  integers.  And if this is not enough and your system supports 64 bit integers you can\npush the limits much closer to infinity with pack codes \"q\" and \"Q\". A notable  exception  is\nprovided  by  pack  codes  \"i\" and \"I\" for signed and unsigned integers of the \"local custom\"\nvariety: Such an integer will take up as many  bytes  as  a  local  C  compiler  returns  for\nsizeof(int), but it'll use at least 32 bits.\n\nEach  of  the integer pack codes \"sSlLqQ\" results in a fixed number of bytes, no matter where\nyou execute your program. This may be useful for some applications, but it does  not  provide\nfor  a portable way to pass data structures between Perl and C programs (bound to happen when\nyou call XS extensions or the Perl function \"syscall\"), or when  you  read  or  write  binary\nfiles.  What  you'll  need  in  this case are template codes that depend on what your local C\ncompiler compiles when you code \"short\" or \"unsigned long\", for  instance.  These  codes  and\ntheir  corresponding  byte lengths are shown in the table below.  Since the C standard leaves\nmuch leeway with respect to the relative sizes of these data types, actual values  may  vary,\nand  that's  why  the  values  are  given as expressions in C and Perl. (If you'd like to use\nvalues from %Config in your program you have to import it with \"use Config\".)\n\nsigned unsigned  byte length in C   byte length in Perl\ns!     S!      sizeof(short)      $Config{shortsize}\ni!     I!      sizeof(int)        $Config{intsize}\nl!     L!      sizeof(long)       $Config{longsize}\nq!     Q!      sizeof(long long)  $Config{longlongsize}\n\nThe \"i!\" and  \"I!\"  codes  aren't  different  from  \"i\"  and  \"I\";  they  are  tolerated  for\ncompleteness' sake.\n"
                },
                {
                    "name": "Unpacking a Stack Frame",
                    "content": "Requesting  a particular byte ordering may be necessary when you work with binary data coming\nfrom some specific architecture whereas your program could run on a totally different system.\nAs an example, assume you have 24 bytes containing a stack frame as it happens  on  an  Intel\n8086:\n\n+---------+        +----+----+               +---------+\nTOS: |   IP    |  TOS+4:| FL | FH | FLAGS  TOS+14:|   SI    |\n+---------+        +----+----+               +---------+\n|   CS    |        | AL | AH | AX            |   DI    |\n+---------+        +----+----+               +---------+\n| BL | BH | BX            |   BP    |\n+----+----+               +---------+\n| CL | CH | CX            |   DS    |\n+----+----+               +---------+\n| DL | DH | DX            |   ES    |\n+----+----+               +---------+\n\nFirst, we note that this time-honored 16-bit CPU uses little-endian order, and that's why the\nlow  order  byte is stored at the lower address. To unpack such a (unsigned) short we'll have\nto use code \"v\". A repeat count unpacks all 12 shorts:\n\nmy( $ip, $cs, $flags, $ax, $bx, $cx, $dx, $si, $di, $bp, $ds, $es ) =\nunpack( 'v12', $frame );\n\nAlternatively, we could have used \"C\" to unpack the individually  accessible  byte  registers\nFL, FH, AL, AH, etc.:\n\nmy( $fl, $fh, $al, $ah, $bl, $bh, $cl, $ch, $dl, $dh ) =\nunpack( 'C10', substr( $frame, 4, 10 ) );\n\nIt would be nice if we could do this in one fell swoop: unpack a short, back up a little, and\nthen  unpack  2  bytes.  Since Perl is nice, it proffers the template code \"X\" to back up one\nbyte. Putting this all together, we may now write:\n\nmy( $ip, $cs,\n$flags,$fl,$fh,\n$ax,$al,$ah, $bx,$bl,$bh, $cx,$cl,$ch, $dx,$dl,$dh,\n$si, $di, $bp, $ds, $es ) =\nunpack( 'v2' . ('vXXCC' x 5) . 'v5', $frame );\n\n(The clumsy construction of the template can be avoided - just read on!)\n\nWe've taken some pains to construct the template so that it matches the contents of our frame\nbuffer. Otherwise we'd either get undefined values, or \"unpack\"  could  not  unpack  all.  If\n\"pack\" runs out of items, it will supply null strings (which are coerced into zeroes whenever\nthe pack code says so).\n"
                },
                {
                    "name": "How to Eat an Egg on a Net",
                    "content": "The  pack  code  for big-endian (high order byte at the lowest address) is \"n\" for 16 bit and\n\"N\" for 32 bit integers. You use these codes  if  you  know  that  your  data  comes  from  a\ncompliant architecture, but, surprisingly enough, you should also use these pack codes if you\nexchange  binary  data,  across  the  network, with some system that you know next to nothing\nabout. The simple reason is that this order has been chosen as the  network  order,  and  all\nstandard-fearing  programs  ought  to  follow  this  convention. (This is, of course, a stern\nbacking for one of the Lilliputian parties and may well influence the  political  development\nthere.)  So,  if  the  protocol  expects  you  to send a message by sending the length first,\nfollowed by just so many bytes, you could write:\n\nmy $buf = pack( 'N', length( $msg ) ) . $msg;\n\nor even:\n\nmy $buf = pack( 'NA*', length( $msg ), $msg );\n\nand pass $buf to your send routine. Some protocols demand that the count should  include  the\nlength  of  the  count  itself:  then  just  add 4 to the data length. (But make sure to read\n\"Lengths and Widths\" before you really code this!)\n"
                },
                {
                    "name": "Byte-order modifiers",
                    "content": "In the previous sections we've learned how to use \"n\", \"N\", \"v\" and \"V\" to  pack  and  unpack\nintegers  with  big-  or  little-endian  byte-order.   While  this is nice, it's still rather\nlimited because it leaves out all kinds of signed integers as well as  64-bit  integers.  For\nexample,  if  you  wanted  to  unpack  a  sequence  of signed big-endian 16-bit integers in a\nplatform-independent way, you would have to write:\n\nmy @data = unpack 's*', pack 'S*', unpack 'n*', $buf;\n\nThis is ugly. As of Perl 5.9.2, there's a much nicer way to express your desire for a certain\nbyte-order: the \">\" and \"<\" modifiers.  \">\" is the big-endian  modifier,  while  \"<\"  is  the\nlittle-endian modifier. Using them, we could rewrite the above code as:\n\nmy @data = unpack 's>*', $buf;\n\nAs  you  can see, the \"big end\" of the arrow touches the \"s\", which is a nice way to remember\nthat \">\" is the big-endian modifier. The same obviously works for \"<\", where the \"little end\"\ntouches the code.\n\nYou will probably find these modifiers even more useful if you have  to  deal  with  big-  or\nlittle-endian  C structures. Be sure to read \"Packing and Unpacking C Structures\" for more on\nthat.\n"
                },
                {
                    "name": "Floating point Numbers",
                    "content": "For packing floating point numbers you have the choice between the pack codes \"f\",  \"d\",  \"F\"\nand  \"D\".  \"f\"  and  \"d\"  pack  into  (or  unpack  from) single-precision or double-precision\nrepresentation as it is provided by your system. If your systems supports it, \"D\" can be used\nto pack and unpack (\"long double\") values, which can offer even more resolution than  \"f\"  or\n\"d\".  Note that there are different long double formats.\n\n\"F\" packs an \"NV\", which is the floating point type used by Perl internally.\n\nThere  is  no  such  thing as a network representation for reals, so if you want to send your\nreal numbers across computer boundaries, you'd better stick to text representation,  possibly\nusing  the  hexadecimal  float  format  (avoiding the decimal conversion loss), unless you're\nabsolutely sure what's on the other end of the line. For the even more adventuresome, you can\nuse the byte-order modifiers from the previous section also on floating point codes.\n"
                }
            ]
        },
        "Exotic Templates": {
            "content": "",
            "subsections": [
                {
                    "name": "Bit Strings",
                    "content": "Bits are the atoms in the memory world. Access to individual bits may have to be used  either\nas  a  last  resort  or because it is the most convenient way to handle your data. Bit string\n(un)packing converts between strings containing a series of 0 and 1 characters and a sequence\nof bytes each containing a group of 8 bits. This is almost as simple  as  it  sounds,  except\nthat  there  are two ways the contents of a byte may be written as a bit string. Let's have a\nlook at an annotated byte:\n\n7 6 5 4 3 2 1 0\n+-----------------+\n| 1 0 0 0 1 1 0 0 |\n+-----------------+\nMSB           LSB\n\nIt's egg-eating all over again: Some think that as  a  bit  string  this  should  be  written\n\"10001100\"  i.e.  beginning with the most significant bit, others insist on \"00110001\". Well,\nPerl isn't biased, so that's why we have two bit string codes:\n\n$byte = pack( 'B8', '10001100' ); # start with MSB\n$byte = pack( 'b8', '00110001' ); # start with LSB\n\nIt is not possible to pack or unpack bit fields - just integral bytes.  \"pack\" always  starts\nat  the  next  byte boundary and \"rounds up\" to the next multiple of 8 by adding zero bits as\nrequired. (If you do want bit fields, there is \"vec\" in perlfunc. Or you could implement  bit\nfield  handling  at  the  character  string  level, using split, substr, and concatenation on\nunpacked bit strings.)\n\nTo illustrate unpacking for bit strings, we'll decompose a  simple  status  register  (a  \"-\"\nstands for a \"reserved\" bit):\n\n+-----------------+-----------------+\n| S Z - A - P - C | - - - - O D I T |\n+-----------------+-----------------+\nMSB           LSB MSB           LSB\n\nConverting  these two bytes to a string can be done with the unpack template 'b16'. To obtain\nthe individual bit values from the bit string we  use  \"split\"  with  the  \"empty\"  separator\npattern  which  dissects into individual characters. Bit values from the \"reserved\" positions\nare simply assigned to \"undef\", a convenient notation for \"I don't care where this goes\".\n\n($carry, undef, $parity, undef, $auxcarry, undef, $zero, $sign,\n$trace, $interrupt, $direction, $overflow) =\nsplit( //, unpack( 'b16', $status ) );\n\nWe could have used an unpack template 'b12' just as well,  since  the  last  4  bits  can  be\nignored anyway.\n"
                },
                {
                    "name": "Uuencoding",
                    "content": "Another  odd-man-out in the template alphabet is \"u\", which packs a \"uuencoded string\". (\"uu\"\nis short for Unix-to-Unix.) Chances are that you won't  ever  need  this  encoding  technique\nwhich was invented to overcome the shortcomings of old-fashioned transmission mediums that do\nnot  support  other than simple ASCII data. The essential recipe is simple: Take three bytes,\nor 24 bits. Split them into 4 six-packs, adding a space (0x20) to each. Repeat until  all  of\nthe  data is blended. Fold groups of 4 bytes into lines no longer than 60 and garnish them in\nfront with the original byte count (incremented by 0x20) and a \"\\n\" at the end. - The  \"pack\"\nchef will prepare this for you, a la minute, when you select pack code \"u\" on the menu:\n\nmy $uubuf = pack( 'u', $bindat );\n\nA repeat count after \"u\" sets the number of bytes to put into an uuencoded line, which is the\nmaximum  of  45  by  default,  but  could be set to some (smaller) integer multiple of three.\n\"unpack\" simply ignores the repeat count.\n"
                },
                {
                    "name": "Doing Sums",
                    "content": "An even stranger template code is \"%\"<number>. First, because it's used as a prefix  to  some\nother  template  code.  Second,  because  it  cannot  be used in \"pack\" at all, and third, in\n\"unpack\", doesn't return the data as defined by the template code it precedes. Instead  it'll\ngive  you  an  integer of number bits that is computed from the data value by doing sums. For\nnumeric unpack codes, no big feat is achieved:\n\nmy $buf = pack( 'iii', 100, 20, 3 );\nprint unpack( '%32i3', $buf ), \"\\n\";  # prints 123\n\nFor string values, \"%\" returns the sum of the byte values saving you the  trouble  of  a  sum\nloop with \"substr\" and \"ord\":\n\nprint unpack( '%32A*', \"\\x01\\x10\" ), \"\\n\";  # prints 17\n\nAlthough  the  \"%\" code is documented as returning a \"checksum\": don't put your trust in such\nvalues! Even when applied to a small number of  bytes,  they  won't  guarantee  a  noticeable\nHamming distance.\n\nIn connection with \"b\" or \"B\", \"%\" simply adds bits, and this can be put to good use to count\nset bits efficiently:\n\nmy $bitcount = unpack( '%32b*', $mask );\n\nAnd an even parity bit can be determined like this:\n\nmy $evenparity = unpack( '%1b*', $mask );\n"
                },
                {
                    "name": "Unicode",
                    "content": "Unicode  is  a  character  set  that  can  represent  most  characters in most of the world's\nlanguages, providing room for over one million different characters.  Unicode  3.1  specifies\n94,140  characters:  The  Basic  Latin  characters  are  assigned to the numbers 0 - 127. The\nLatin-1 Supplement with characters that are used in several European languages is in the next\nrange, up to 255. After some more Latin extensions we find the character sets from  languages\nusing  non-Roman  alphabets,  interspersed  with  a  variety  of symbol sets such as currency\nsymbols, Zapf Dingbats or Braille.  (You might want to visit <https://www.unicode.org/> for a\nlook at some of them - my personal favourites are Telugu and Kannada.)\n\nThe Unicode character sets associates characters with integers. Encoding these numbers in  an\nequal  number  of  bytes would more than double the requirements for storing texts written in\nLatin alphabets.  The UTF-8 encoding avoids this by storing the most common (from  a  western\npoint  of  view)  characters  in a single byte while encoding the rarer ones in three or more\nbytes.\n\nPerl uses UTF-8, internally, for most Unicode strings.\n\nSo what has this got to do with \"pack\"? Well, if you want to compose a Unicode  string  (that\nis  internally  encoded  as  UTF-8), you can do so by using template code \"U\". As an example,\nlet's produce the Euro currency symbol (code number 0x20AC):\n\n$UTF8{Euro} = pack( 'U', 0x20AC );\n# Equivalent to: $UTF8{Euro} = \"\\x{20ac}\";\n\nInspecting $UTF8{Euro} shows that it contains 3 bytes: \"\\xe2\\x82\\xac\". However,  it  contains\nonly 1 character, number 0x20AC.  The round trip can be completed with \"unpack\":\n\n$Unicode{Euro} = unpack( 'U', $UTF8{Euro} );\n\nUnpacking using the \"U\" template code also works on UTF-8 encoded byte strings.\n\nUsually you'll want to pack or unpack UTF-8 strings:\n\n# pack and unpack the Hebrew alphabet\nmy $alefbet = pack( 'U*', 0x05d0..0x05ea );\nmy @hebrew = unpack( 'U*', $utf );\n\nPlease  note: in the general case, you're better off using \"Encode::decode('UTF-8', $utf)\" to\ndecode a UTF-8 encoded byte string to a Perl  Unicode  string,  and  \"Encode::encode('UTF-8',\n$str)\"  to  encode  a  Perl  Unicode  string to UTF-8 bytes. These functions provide means of\nhandling invalid byte sequences and generally have a friendlier interface.\n"
                },
                {
                    "name": "Another Portable Binary Encoding",
                    "content": "The pack code \"w\" has been added to support a portable binary data encoding scheme that  goes\nway       beyond      simple      integers.      (Details      can      be      found      at\n<https://github.com/mworks-project/mwscarab/blob/master/Scarab-0.1.00d19/doc/binary-serialization.txt>,\nthe Scarab project.)  A BER  (Binary  Encoded  Representation)  compressed  unsigned  integer\nstores  base  128  digits, most significant digit first, with as few digits as possible.  Bit\neight (the high bit) is set on each byte except the last. There  is  no  size  limit  to  BER\nencoding, but Perl won't go to extremes.\n\nmy $berbuf = pack( 'w*', 1, 128, 128+1, 128*128+127 );\n\nA  hex  dump of $berbuf, with spaces inserted at the right places, shows 01 8100 8101 81807F.\nSince the last byte is always less than 128, \"unpack\" knows where to stop.\n"
                }
            ]
        },
        "Template Grouping": {
            "content": "Prior to Perl 5.8, repetitions of templates had to be made by \"x\"-multiplication of  template\nstrings.  Now  there is a better way as we may use the pack codes \"(\" and \")\" combined with a\nrepeat count.  The \"unpack\" template from the Stack Frame example can simply be written  like\nthis:\n\nunpack( 'v2 (vXXCC)5 v5', $frame )\n\nLet's explore this feature a little more. We'll begin with the equivalent of\n\njoin( '', map( substr( $, 0, 1 ), @str ) )\n\nwhich  returns  a  string consisting of the first character from each string.  Using pack, we\ncan write\n\npack( '(A)'.@str, @str )\n\nor, because a repeat count \"*\" means \"repeat as often as required\", simply\n\npack( '(A)*', @str )\n\n(Note that the template \"A*\" would only have packed $str[0] in full length.)\n\nTo pack dates stored as triplets ( day, month, year ) in an array @dates into a  sequence  of\nbyte, byte, short integer we can write\n\n$pd = pack( '(CCS)*', map( @$, @dates ) );\n\nTo  swap pairs of characters in a string (with even length) one could use several techniques.\nFirst, let's use \"x\" and \"X\" to skip forward and back:\n\n$s = pack( '(A)*', unpack( '(xAXXAx)*', $s ) );\n\nWe can also use \"@\" to jump to an offset, with 0 being the position where we  were  when  the\nlast \"(\" was encountered:\n\n$s = pack( '(A)*', unpack( '(@1A @0A @2)*', $s ) );\n\nFinally,  there  is  also  an  entirely different approach by unpacking big endian shorts and\npacking them in the reverse byte order:\n\n$s = pack( '(v)*', unpack( '(n)*', $s );\n",
            "subsections": []
        },
        "Lengths and Widths": {
            "content": "",
            "subsections": [
                {
                    "name": "String Lengths",
                    "content": "In the previous section we've seen a network message that was constructed  by  prefixing  the\nbinary message length to the actual message. You'll find that packing a length followed by so\nmany  bytes  of  data is a frequently used recipe since appending a null byte won't work if a\nnull byte may be part of the data. Here is an example where both techniques are  used:  after\ntwo null terminated strings with source and destination address, a Short Message (to a mobile\nphone) is sent after a length byte:\n\nmy $msg = pack( 'Z*Z*CA*', $src, $dst, length( $sm ), $sm );\n\nUnpacking this message can be done with the same template:\n\n( $src, $dst, $len, $sm ) = unpack( 'Z*Z*CA*', $msg );\n\nThere's a subtle trap lurking in the offing: Adding another field after the Short Message (in\nvariable $sm) is all right when packing, but this cannot be unpacked naively:\n\n# pack a message\nmy $msg = pack( 'Z*Z*CA*C', $src, $dst, length( $sm ), $sm, $prio );\n\n# unpack fails - $prio remains undefined!\n( $src, $dst, $len, $sm, $prio ) = unpack( 'Z*Z*CA*C', $msg );\n\nThe pack code \"A*\" gobbles up all remaining bytes, and $prio remains undefined! Before we let\ndisappointment  dampen  the  morale: Perl's got the trump card to make this trick too, just a\nlittle further up the sleeve.  Watch this:\n\n# pack a message: ASCIIZ, ASCIIZ, length/string, byte\nmy $msg = pack( 'Z* Z* C/A* C', $src, $dst, $sm, $prio );\n\n# unpack\n( $src, $dst, $sm, $prio ) = unpack( 'Z* Z* C/A* C', $msg );\n\nCombining two pack codes with a slash (\"/\") associates them with  a  single  value  from  the\nargument  list.  In  \"pack\",  the length of the argument is taken and packed according to the\nfirst code while the argument itself is added after being converted with  the  template  code\nafter  the  slash.   This  saves  us the trouble of inserting the \"length\" call, but it is in\n\"unpack\" where we really score: The value of the length byte marks the end of the  string  to\nbe  taken  from  the buffer. Since this combination doesn't make sense except when the second\npack code isn't \"a*\", \"A*\" or \"Z*\", Perl won't let you.\n\nThe pack code preceding \"/\" may be anything that's fit to represent a number: All the numeric\nbinary pack codes, and even text codes such as \"A4\" or \"Z*\":\n\n# pack/unpack a string preceded by its length in ASCII\nmy $buf = pack( 'A4/A*', \"Humpty-Dumpty\" );\n# unpack $buf: '13  Humpty-Dumpty'\nmy $txt = unpack( 'A4/A*', $buf );\n\n\"/\" is not implemented in Perls before 5.6, so if your code is required to  work  on  ancient\nPerls you'll need to \"unpack( 'Z* Z* C')\" to get the length, then use it to make a new unpack\nstring. For example\n\n# pack a message: ASCIIZ, ASCIIZ, length, string, byte\n# (5.005 compatible)\nmy $msg = pack( 'Z* Z* C A* C', $src, $dst, length $sm, $sm, $prio );\n\n# unpack\n( undef, undef, $len) = unpack( 'Z* Z* C', $msg );\n($src, $dst, $sm, $prio) = unpack ( \"Z* Z* x A$len C\", $msg );\n\nBut  that  second  \"unpack\"  is rushing ahead. It isn't using a simple literal string for the\ntemplate. So maybe we should introduce...\n"
                },
                {
                    "name": "Dynamic Templates",
                    "content": "So far, we've seen literals used as templates. If the list of pack items doesn't  have  fixed\nlength, an expression constructing the template is required (whenever, for some reason, \"()*\"\ncannot  be  used).   Here's  an  example:  To  store named string values in a way that can be\nconveniently parsed by a C program, we create a sequence of names and null  terminated  ASCII\nstrings,  with  \"=\" between the name and the value, followed by an additional delimiting null\nbyte. Here's how:\n\nmy $env = pack( '(A*A*Z*)' . keys( %Env ) . 'C',\nmap( { ( $, '=', $Env{$} ) } keys( %Env ) ), 0 );\n\nLet's examine the cogs of this byte mill, one by one. There's the \"map\"  call,  creating  the\nitems  we intend to stuff into the $env buffer: to each key (in $) it adds the \"=\" separator\nand the hash entry value.  Each triplet is packed with the template  code  sequence  \"A*A*Z*\"\nthat  is  repeated  according  to  the  number of keys. (Yes, that's what the \"keys\" function\nreturns in scalar context.) To get the very last null byte, we add a 0  at  the  end  of  the\n\"pack\"  list,  to be packed with \"C\".  (Attentive readers may have noticed that we could have\nomitted the 0.)\n\nFor the reverse operation, we'll have to determine the number of items in the  buffer  before\nwe can let \"unpack\" rip it apart:\n\nmy $n = $env =~ tr/\\0// - 1;\nmy %env = map( split( /=/, $ ), unpack( \"(Z*)$n\", $env ) );\n\nThe  \"tr\" counts the null bytes. The \"unpack\" call returns a list of name-value pairs each of\nwhich is taken apart in the \"map\" block.\n"
                },
                {
                    "name": "Counting Repetitions",
                    "content": "Rather than storing a sentinel at the end of a data item (or  a  list  of  items),  we  could\nprecede  the data with a count. Again, we pack keys and values of a hash, preceding each with\nan unsigned short length count, and up front we store the number of pairs:\n\nmy $env = pack( 'S(S/A* S/A*)*', scalar keys( %Env ), %Env );\n\nThis simplifies the reverse operation as the number of repetitions can be unpacked  with  the\n\"/\" code:\n\nmy %env = unpack( 'S/(S/A* S/A*)', $env );\n\nNote that this is one of the rare cases where you cannot use the same template for \"pack\" and\n\"unpack\" because \"pack\" can't determine a repeat count for a \"()\"-group.\n"
                },
                {
                    "name": "Intel HEX",
                    "content": "Intel  HEX  is  a  file  format  for representing binary data, mostly for programming various\nchips, as a text file. (See <https://en.wikipedia.org/wiki/.hex> for a detailed  description,\nand  <https://en.wikipedia.org/wiki/SREC(fileformat)>  for  the  Motorola  S-record format,\nwhich can be unravelled using the same technique.)  Each line begins with a colon  (':')  and\nis  followed  by  a sequence of hexadecimal characters, specifying a byte count n (8 bit), an\naddress (16 bit, big endian), a record type (8 bit), n data bytes  and  a  checksum  (8  bit)\ncomputed  as  the  least significant byte of the two's complement sum of the preceding bytes.\nExample: \":0300300002337A1E\".\n\nThe first step of processing such a line is the conversion, to  binary,  of  the  hexadecimal\ndata,  to  obtain the four fields, while checking the checksum. No surprise here: we'll start\nwith a simple \"pack\" call to convert everything to binary:\n\nmy $binrec = pack( 'H*', substr( $hexrec, 1 ) );\n\nThe resulting byte sequence is most convenient for checking the checksum.   Don't  slow  your\nprogram  down  with  a for loop adding the \"ord\" values of this string's bytes - the \"unpack\"\ncode \"%\" is the thing to use for computing the 8-bit sum of all bytes, which must be equal to\nzero:\n\ndie unless unpack( \"%8C*\", $binrec ) == 0;\n\nFinally, let's get those four fields. By now, you shouldn't have any problems with the  first\nthree  fields  - but how can we use the byte count of the data in the first field as a length\nfor the data field? Here the codes \"x\" and \"X\" come to the rescue,  as  they  permit  jumping\nback and forth in the string to unpack.\n\nmy( $addr, $type, $data ) = unpack( \"x n C X4 C x3 /a\", $bin );\n\nCode  \"x\"  skips a byte, since we don't need the count yet. Code \"n\" takes care of the 16-bit\nbig-endian integer address, and \"C\" unpacks the record type. Being at  offset  4,  where  the\ndata  begins,  we  need  the  count.  \"X4\" brings us back to square one, which is the byte at\noffset 0.  Now we pick up the count, and zoom forth to offset  4,  where  we  are  now  fully\nfurnished  to  extract  the  exact  number  of data bytes, leaving the trailing checksum byte\nalone.\n"
                }
            ]
        },
        "Packing and Unpacking C Structures": {
            "content": "In previous sections we have seen how to pack numbers and character strings. If it  were  not\nfor  a couple of snags we could conclude this section right away with the terse remark that C\nstructures don't contain anything else, and therefore you already know all there  is  to  it.\nSorry, no: read on, please.\n\nIf  you  have  to  deal  with a lot of C structures, and don't want to hack all your template\nstrings  manually,  you'll  probably   want   to   have   a   look   at   the   CPAN   module\n\"Convert::Binary::C\".  Not only can it parse your C source directly, but it also has built-in\nsupport for all the odds and ends described further on in this section.\n",
            "subsections": [
                {
                    "name": "The Alignment Pit",
                    "content": "In the consideration of speed against memory requirements the  balance  has  been  tilted  in\nfavor  of  faster  execution.  This  has  influenced  the way C compilers allocate memory for\nstructures: On architectures where a 16-bit or 32-bit operand can  be  moved  faster  between\nplaces  in  memory, or to or from a CPU register, if it is aligned at an even or multiple-of-\nfour or even at a multiple-of eight address, a C compiler will give you this speed benefit by\nstuffing extra bytes into structures.  If you don't cross the C shoreline this is not  likely\nto  cause  you  any grief (although you should care when you design large data structures, or\nyou want your code to be portable between architectures (you do want that, don't you?)).\n\nTo see how this affects \"pack\" and \"unpack\", we'll compare these two C structures:\n\ntypedef struct {\nchar     c1;\nshort    s;\nchar     c2;\nlong     l;\n} gappyt;\n\ntypedef struct {\nlong     l;\nshort    s;\nchar     c1;\nchar     c2;\n} denset;\n\nTypically, a C compiler allocates 12 bytes to a \"gappyt\" variable, but requires only 8 bytes\nfor a \"denset\". After investigating this further, we can draw memory maps, showing where the\nextra 4 bytes are hidden:\n\n0           +4          +8          +12\n+--+--+--+--+--+--+--+--+--+--+--+--+\n|c1|xx|  s  |c2|xx|xx|xx|     l     |    xx = fill byte\n+--+--+--+--+--+--+--+--+--+--+--+--+\ngappyt\n\n0           +4          +8\n+--+--+--+--+--+--+--+--+\n|     l     |  h  |c1|c2|\n+--+--+--+--+--+--+--+--+\ndenset\n\nAnd that's where the first quirk strikes: \"pack\" and \"unpack\" templates have  to  be  stuffed\nwith \"x\" codes to get those extra fill bytes.\n\nThe  natural question: \"Why can't Perl compensate for the gaps?\" warrants an answer. One good\nreason is that C compilers might provide (non-ANSI) extensions permitting all sorts of  fancy\ncontrol  over  the  way  structures are aligned, even at the level of an individual structure\nfield. And, if this were not enough, there is an insidious thing  called  \"union\"  where  the\namount of fill bytes cannot be derived from the alignment of the next item alone.\n\nOK, so let's bite the bullet. Here's one way to get the alignment right by inserting template\ncodes \"x\", which don't take a corresponding item from the list:\n\nmy $gappy = pack( 'cxs cxxx l!', $c1, $s, $c2, $l );\n\nNote the \"!\" after \"l\": We want to make sure that we pack a long integer as it is compiled by\nour  C  compiler. And even now, it will only work for the platforms where the compiler aligns\nthings as above.  And somebody somewhere has a platform where it doesn't.  [Probably a  Cray,\nwhere \"short\"s, \"int\"s and \"long\"s are all 8 bytes. :-)]\n\nCounting  bytes  and  watching  alignments in lengthy structures is bound to be a drag. Isn't\nthere a way we can create the template with a simple program? Here's a C  program  that  does\nthe trick:\n\n#include <stdio.h>\n#include <stddef.h>\n\ntypedef struct {\nchar     fc1;\nshort    fs;\nchar     fc2;\nlong     fl;\n} gappyt;\n\n#define Pt(struct,field,tchar) \\\nprintf( \"@%d%s \", offsetof(struct,field), # tchar );\n\nint main() {\nPt( gappyt, fc1, c  );\nPt( gappyt, fs,  s! );\nPt( gappyt, fc2, c  );\nPt( gappyt, fl,  l! );\nprintf( \"\\n\" );\n}\n\nThe output line can be used as a template in a \"pack\" or \"unpack\" call:\n\nmy $gappy = pack( '@0c @2s! @4c @8l!', $c1, $s, $c2, $l );\n\nGee, yet another template code - as if we hadn't plenty. But \"@\" saves our day by enabling us\nto  specify  the  offset from the beginning of the pack buffer to the next item: This is just\nthe value the \"offsetof\" macro (defined in \"<stddef.h>\") returns when given a  \"struct\"  type\nand one of its field names (\"member-designator\" in C standardese).\n\nNeither  using  offsets  nor  adding \"x\"'s to bridge the gaps is satisfactory.  (Just imagine\nwhat happens if the structure changes.) What we really need is a way of saying \"skip as  many\nbytes  as  required to the next multiple of N\".  In fluent templates, you say this with \"x!N\"\nwhere N is replaced by  the  appropriate  value.  Here's  the  next  version  of  our  struct\npackaging:\n\nmy $gappy = pack( 'c x!2 s c x!4 l!', $c1, $s, $c2, $l );\n\nThat's  certainly  better,  but  we  still  have  to  know how long all the integers are, and\nportability is far away. Rather than 2, for instance, we want to say \"however  long  a  short\nis\".  But  this  can  be  done by enclosing the appropriate pack code in brackets: \"[s]\". So,\nhere's the very best we can do:\n\nmy $gappy = pack( 'c x![s] s c x![l!] l!', $c1, $s, $c2, $l );\n"
                },
                {
                    "name": "Dealing with Endian-ness",
                    "content": "Now, imagine that we want to pack the data for a machine with a different byte-order.  First,\nwe'll  have  to  figure  out  how  big the data types on the target machine really are. Let's\nassume that the longs are 32 bits wide and the shorts are 16 bits wide. You can then  rewrite\nthe template as:\n\nmy $gappy = pack( 'c x![s] s c x![l] l', $c1, $s, $c2, $l );\n\nIf the target machine is little-endian, we could write:\n\nmy $gappy = pack( 'c x![s] s< c x![l] l<', $c1, $s, $c2, $l );\n\nThis forces the short and the long members to be little-endian, and is just fine if you don't\nhave  too  many  struct members. But we could also use the byte-order modifier on a group and\nwrite the following:\n\nmy $gappy = pack( '( c x![s] s c x![l] l )<', $c1, $s, $c2, $l );\n\nThis is not as short as before, but it makes it more obvious that we intend to  have  little-\nendian  byte-order  for a whole group, not only for individual template codes. It can also be\nmore readable and easier to maintain.\n"
                },
                {
                    "name": "Alignment, Take 2",
                    "content": "I'm afraid that we're not quite through with  the  alignment  catch  yet.  The  hydra  raises\nanother ugly head when you pack arrays of structures:\n\ntypedef struct {\nshort    count;\nchar     glyph;\n} cellt;\n\ntypedef cellt buffert[BUFLEN];\n\nWhere's  the  catch?  Padding is neither required before the first field \"count\", nor between\nthis and the next field \"glyph\", so why can't we simply pack like this:\n\n# something goes wrong here:\npack( 's!a' x @buffer,\nmap{ ( $->{count}, $->{glyph} ) } @buffer );\n\nThis packs \"3*@buffer\" bytes, but it turns out that the size  of  \"buffert\"  is  four  times\n\"BUFLEN\"!  The  moral  of the story is that the required alignment of a structure or array is\npropagated to the next higher level where we have to consider padding  at  the  end  of  each\ncomponent as well. Thus the correct template is:\n\npack( 's!ax' x @buffer,\nmap{ ( $->{count}, $->{glyph} ) } @buffer );\n"
                },
                {
                    "name": "Alignment, Take 3",
                    "content": "And even if you take all the above into account, ANSI still lets this:\n\ntypedef struct {\nchar     foo[2];\n} foot;\n\nvary  in  size.  The  alignment  constraint  of  the structure can be greater than any of its\nelements. [And if you think that this doesn't affect  anything  common,  dismember  the  next\ncellphone  that  you  see.  Many  have  ARM  cores,  and the ARM structure rules make \"sizeof\n(foot)\" == 4]\n"
                },
                {
                    "name": "Pointers for How to Use Them",
                    "content": "The title of this section indicates the second problem you may run into sooner or later  when\nyou pack C structures. If the function you intend to call expects a, say, \"void *\" value, you\ncannot simply take a reference to a Perl variable. (Although that value certainly is a memory\naddress, it's not the address where the variable's contents are stored.)\n\nTemplate  code \"P\" promises to pack a \"pointer to a fixed length string\".  Isn't this what we\nwant? Let's try:\n\n# allocate some storage and pack a pointer to it\nmy $memory = \"\\x00\" x $size;\nmy $memptr = pack( 'P', $memory );\n\nBut wait: doesn't \"pack\" just return a sequence of bytes? How can  we  pass  this  string  of\nbytes  to  some  C  code  expecting  a pointer which is, after all, nothing but a number? The\nanswer is simple: We have to obtain the numeric address from the bytes returned by \"pack\".\n\nmy $ptr = unpack( 'L!', $memptr );\n\nObviously this assumes that it is possible to typecast a pointer to an unsigned long and vice\nversa, which frequently works but should not be taken as a universal law. - Now that we  have\nthis  pointer  the  next question is: How can we put it to good use? We need a call to some C\nfunction where a pointer is expected. The read(2) system call comes to mind:\n\nssizet read(int fd, void *buf, sizet count);\n\nAfter reading perlfunc explaining how to use  \"syscall\"  we  can  write  this  Perl  function\ncopying a file to standard output:\n\nrequire 'syscall.ph'; # run h2ph to generate this file\nsub cat($){\nmy $path = shift();\nmy $size = -s $path;\nmy $memory = \"\\x00\" x $size;  # allocate some memory\nmy $ptr = unpack( 'L', pack( 'P', $memory ) );\nopen( F, $path ) || die( \"$path: cannot open ($!)\\n\" );\nmy $fd = fileno(F);\nmy $res = syscall( &SYSread, fileno(F), $ptr, $size );\nprint $memory;\nclose( F );\n}\n\nThis  is neither a specimen of simplicity nor a paragon of portability but it illustrates the\npoint: We are able to sneak behind  the  scenes  and  access  Perl's  otherwise  well-guarded\nmemory!  (Important note: Perl's \"syscall\" does not require you to construct pointers in this\nroundabout way. You simply pass a string variable, and Perl forwards the address.)\n\nHow does \"unpack\" with \"P\" work? Imagine some pointer in the buffer about to be unpacked:  If\nit  isn't  the  null  pointer  (which will smartly produce the \"undef\" value) we have a start\naddress - but then what?  Perl has no way of knowing how long this \"fixed length string\"  is,\nso it's up to you to specify the actual size as an explicit length after \"P\".\n\nmy $mem = \"abcdefghijklmn\";\nprint unpack( 'P5', pack( 'P', $mem ) ); # prints \"abcde\"\n\nAs a consequence, \"pack\" ignores any number or \"*\" after \"P\".\n\nNow  that  we  have  seen  \"P\"  at work, we might as well give \"p\" a whirl.  Why do we need a\nsecond template code for packing pointers at all? The answer lies behind the simple fact that\nan \"unpack\" with \"p\" promises a null-terminated string starting at the address taken from the\nbuffer, and that implies a length for the data item to be returned:\n\nmy $buf = pack( 'p', \"abc\\x00efhijklmn\" );\nprint unpack( 'p', $buf );    # prints \"abc\"\n\nAlbeit this is apt to be confusing: As a consequence of  the  length  being  implied  by  the\nstring's length, a number after pack code \"p\" is a repeat count, not a length as after \"P\".\n\nUsing  \"pack(..., $x)\" with \"P\" or \"p\" to get the address where $x is actually stored must be\nused with circumspection. Perl's internal machinery considers the relation between a variable\nand that address as its very own private matter and doesn't really care that we have obtained\na copy. Therefore:\n\n•   Do not use \"pack\" with \"p\" or \"P\" to obtain the address of variable that's  bound  to  go\nout  of  scope (and thereby freeing its memory) before you are done with using the memory\nat that address.\n\n•   Be very careful with Perl operations that change the value  of  the  variable.  Appending\nsomething  to  the  variable,  for  instance,  might require reallocation of its storage,\nleaving you with a pointer into no-man's land.\n\n•   Don't think that you can get the address of a Perl variable  when  it  is  stored  as  an\ninteger   or   double   number!  \"pack('P',  $x)\"  will  force  the  variable's  internal\nrepresentation to string, just as if you had written something like \"$x .= ''\".\n\nIt's safe, however, to P- or p-pack a  string  literal,  because  Perl  simply  allocates  an\nanonymous variable.\n"
                }
            ]
        },
        "Pack Recipes": {
            "content": "Here are a collection of (possibly) useful canned recipes for \"pack\" and \"unpack\":\n\n# Convert IP address for socket functions\npack( \"C4\", split /\\./, \"123.4.5.6\" );\n\n# Count the bits in a chunk of memory (e.g. a select vector)\nunpack( '%32b*', $mask );\n\n# Determine the endianness of your system\n$islittleendian = unpack( 'c', pack( 's', 1 ) );\n$isbigendian = unpack( 'xc', pack( 's', 1 ) );\n\n# Determine the number of bits in a native integer\n$bits = unpack( '%32I!', ~0 );\n\n# Prepare argument for the nanosleep system call\nmy $timespec = pack( 'L!L!', $secs, $nanosecs );\n\nFor  a simple memory dump we unpack some bytes into just as many pairs of hex digits, and use\n\"map\" to handle the traditional spacing - 16 bytes to a line:\n\nmy $i;\nprint map( ++$i % 16 ? \"$ \" : \"$\\n\",\nunpack( 'H2' x length( $mem ), $mem ) ),\nlength( $mem ) % 16 ? \"\\n\" : '';\n",
            "subsections": []
        },
        "Funnies Section": {
            "content": "# Pulling digits out of nowhere...\nprint unpack( 'C', pack( 'x' ) ),\nunpack( '%B*', pack( 'A' ) ),\nunpack( 'H', pack( 'A' ) ),\nunpack( 'A', unpack( 'C', pack( 'A' ) ) ), \"\\n\";\n\n# One for the road ;-)\nmy $advice = pack( 'all u can in a van' );\n",
            "subsections": []
        },
        "Authors": {
            "content": "Simon Cozens and Wolfgang Laun.\n\nperl v5.38.2                                 2026-08-18                               PERLPACKTUT(1)",
            "subsections": []
        }
    },
    "summary": "perlpacktut - tutorial on \"pack\" and \"unpack\"",
    "flags": [],
    "examples": [],
    "see_also": []
}