PERLPACKTUT(1)
PERLPACKTUT(1) π¦β¨
Perl Programmers Reference Guide
NAME π
perlpacktut β tutorial on pack and unpack π
DESCRIPTION π
okay so bestie, gather round π«Ά pack and unpack 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. no cap, it's giving public service announcement π
The Basic Principle π§
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 sizeof 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. iconic C behavior, honestly π₯
In Perl, you just can't access memory at random, but the structural and representational conversion provided by pack and unpack is an excellent alternative. The pack function converts values to a byte sequence containing representations according to a given specification, the so-called "template" argument. unpack 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.) π the way that some things pack but don't unpack is lowkey tragic.
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: syscall 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. slay π
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 unpack, 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 $mem holds a sequence of bytes that we'd like to inspect without assuming anything about its meaning, we can write
my( $hex ) = unpack( 'H*', $mem );
print "$hex\n";
whereupon we might see something like this, with each pair of hex digits corresponding to a byte:
41204d414e204120504c414e20412043414e414c2050414e414d41
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 0x40 - 0x5A indicate an uppercase letter, and 0x20 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 me having flashbacks to ASCII tables π but anyway, not caring too much about which way to read this, we note that unpack with the template code H converts the contents of a sequence of bytes into the customary hexadecimal notation. Since "a sequence of" is a pretty vague indication of quantity, H 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. periodt π
The inverse operation - packing byte contents from a string of hexadecimal digits - is just as easily written. For instance:
my $s = pack( 'H2' x 10, 30..39 );
print "$s\n";
Since we feed a list of ten 2-digit hexadecimal strings to pack, the pack template should contain ten pack codes. If this is run on a computer with ASCII character coding, it will print 0123456789. β¨
π Packing Text π
okay so picture this bestie: you've got a data file that looks like this:
Date |Description | Income|Expenditure
01/24/2001 Zed's Camel Emporium 1147.99
01/28/2001 Flea spray 24.99
01/29/2001 Camel rides to tourists 235.00
and you need to read it in. so how do we even do that??
your first instinct might be split, right? like, obviously. except no β split collapses blank fields, so you'd never know whether a record was income or expenditure. oops. π
ok fine, you could always use substr:
while (<>) {
my $date = substr($_, 0, 11);
my $desc = substr($_, 12, 27);
my $income = substr($_, 40, 7);
my $expend = substr($_, 52, 7);
...
}
and likeβ¦ it's not really a barrel of laughs, is it? π it's honestly worse than it looks too, because the eagle-eyed among you will notice that first field should only be 10 characters wide β and that error has now propagated right on through every other number, which we had to count by hand. so it's error-prone and horribly unfriendly. not the vibe. π
or maybe regular expressions??
while (<>) {
my($date, $desc, $income, $expend) =
m|(\d\d/\d\d/\d{4}) (.{27}) (.{7})(.*)|;
...
}
urgh. it's a bit better, sure, butβ¦ would you want to maintain that? be honest. π
so hey β isn't Perl supposed to make this sort of thing easy? π₯Ί well babes, it does, if you use the right tools. pack and unpack are literally designed to help you out when you're dealing with fixed-width data like the above. so let's look at a solution with unpack:
while (<>) {
my($date, $desc, $income, $expend) = unpack("A10xA27xA7A*", $_);
...
}
ok that looks a bit nicer β¨ but now we've gotta take apart that weird template. where did I even pull that out of?? π§
alright, let's look at our data again β and this time we'll bring the headers and a handy ruler so we can actually keep track of where we are:
1 2 3 4 5
1234567890123456789012345678901234567890123456789012345678
Date |Description | Income|Expenditure
01/28/2001 Flea spray 24.99
01/29/2001 Camel rides to tourists 235.00
from this we can see the date column stretches from column 1 to column 10 β ten characters wide. the pack-ese for "character" is A, and ten of them are A10. so if we just wanted the dates, we could say this:
my($date) = unpack("A10", $_);
ok what's next? between the date and the description there's a blank column, and we wanna skip over it. the x template means "skip forward", so we want one of those. then we've got another batch of characters, from 12 to 38. that's 27 more characters, hence A27.
(and do not make the fencepost error β there are 27 characters between 12 and 38, not 26. count 'em bestie!! π’)
now we skip another character and pick up the next 7 characters:
my($date,$description,$income) = unpack("A10xA27xA7", $_);
now comes the clever bit. π lines in our ledger that are just income and not expenditure might end at column 46. so we don't wanna tell our unpack pattern that we need to find another 12 characters; we just say "if there's anything left, take it". and like you might guess from regular expressions, that's what the * means: "use everything remaining". β¨
- Be warned though β unlike regular expressions, if the
unpacktemplate doesn't match the incoming data, Perl will scream and die. π
so, putting it all together:
my ($date, $description, $income, $expend) =
unpack("A10xA27xA7xA*", $_);
and boom, that's our data parsed. π now I guess what we wanna do is total up our income and expenditure, and add another line to the end of our ledger β same format obviously β saying how much we've brought in and how much we've spent:
while (<>) {
my ($date, $desc, $income, $expend) =
unpack("A10xA27xA7xA*", $_);
$tot_income += $income;
$tot_expend += $expend;
}
$tot_income = sprintf("%.2f", $tot_income); # Get them into
$tot_expend = sprintf("%.2f", $tot_expend); # "financial" format
$date = POSIX::strftime("%m/%d/%Y", localtime);
# OK, let's go:
print pack("A10xA27xA7xA*", $date, "Totals",
$tot_income, $tot_expend);
oh. hmm. π that didn't quite work. let's see what happened:
01/24/2001 Zed's Camel Emporium 1147.99
01/28/2001 Flea spray 24.99
01/29/2001 Camel rides to tourists 1235.00
03/23/2001Totals 1235.001172.98
ok so it's a start, but what happened to the spaces?? we put x, didn't we? shouldn't it skip forward? so let's look at what pack in perlfunc actually says:
x A null byte.
urgh. no wonder. π there's a big difference between "a null byte", character zero, and "a space", character 32. Perl put something between the date and the description β but unfortunately, we can't see it!
what we actually need to do is expand the width of the fields. the A format pads any non-existent characters with spaces, so we can use those extra spaces to line up our fields, like this:
print pack("A11 A28 A8 A*", $date, "Totals",
$tot_income, $tot_expend);
(note that you can put spaces in the template to make it more readable, but they don't translate to spaces in the output. iykyk β¨)
here's what we got this time:
01/24/2001 Zed's Camel Emporium 1147.99
01/28/2001 Flea spray 24.99
01/29/2001 Camel rides to tourists 1235.00
03/23/2001 Totals 1235.00 1172.98
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 pack to right-justify our fields, but we can get sprintf to do it:
$tot_income = sprintf("%.2f", $tot_income);
$tot_expend = sprintf("%12.2f", $tot_expend);
$date = POSIX::strftime("%m/%d/%Y", localtime);
print pack("A11 A28 A8 A*", $date, "Totals",
$tot_income, $tot_expend);
and this time we get the right answer: π
01/28/2001 Flea spray 24.99
01/29/2001 Camel rides to tourists 1235.00
03/23/2001 Totals 1235.00 1172.98
so that's how we consume and produce fixed-width data. π
let's recap what we've seen of pack and unpack so far:
- use
packto go from several pieces of data to one fixed-width version; useunpackto turn a fixed-width-format string into several pieces of data. - the pack format
Ameans "any character"; if you'repacking and you've run out of things to pack,packwill fill the rest up with spaces. xmeans "skip a byte" whenunpacking; whenpacking, it means "introduce a null byte" β that's probably not what you mean if you're dealing with plain text.- you can follow the formats with numbers to say how many characters should be affected by that format:
A12means "take 12 characters";x6means "skip 6 bytes" or "character 0, 6 times". - instead of a number, you can use
*to mean "consume everything else left".
Warning: when packing multiple pieces of data, * only means "consume all of the current piece of data". that's to say
pack("A*A*", $one, $two)
packs all of $one into the first A* and then all of $two into the second. this is a general principle: each format character corresponds to one piece of data to be packed. π«Ά
β¨ Packing Numbers β¨
Okay bestie, text data was cute and all, but now we get to the actual main character energy: pack and unpack doing binary number formats. And no, there isn't just one binary format β because life would be way too easy β but the good news is Perl does all the finicky labor for you. You just vibe. π«Ά
π’ Integers
Packing and unpacking numbers means converting to and from some specific binary representation. Setting floating point aside for a hot sec, here's what matters about any such representation:
- how many bytes the integer takes up π
- whether the contents get read as a signed or unsigned number
- the byte ordering: is the first byte the least significant or the most significant byte (aka little-endian or big-endian respectively) π¦
So like, say you wanna pack 20302 into a signed 16-bit integer using your computer's own representation β you write this:
my $ps = pack( 's', 20302 );
Again: the result is a string, now holding 2 bytes. If you print that string (which, generally, is not recommended π) you might see "ON" or "NO" depending on your system's byte ordering β or something completely different if your computer isn't using ASCII character encoding. And unpacking $ps with the same template hands you back the original integer:
my( $s ) = unpack( 's', $ps );
This holds for all numeric template codes. But don't expect miracles, bestie: if the packed value exceeds the allotted byte capacity, high order bits get silently discarded, and unpack fr fr cannot pull them back out of some magic hat. Also, when you pack with a signed template code like "s", an excess value may result in the sign bit getting set, and unpacking that will smartly hand you back a negative value. π
16 bits won't get you far with integers, but there's "l" and "L" for signed and unsigned 32-bit integers. And if that's still not enough and your system supports 64 bit integers, you can push the limits much closer to infinity with pack codes "q" and "Q". One notable exception: pack codes "i" and "I" for signed and unsigned integers of the "local custom" variety β such an integer takes up as many bytes as a local C compiler returns for sizeof(int), but it'll use at least 32 bits.
Each of the integer pack codes "sSlLqQ" gives you a fixed number of bytes, no matter where you run your program. Useful for some applications, sure β but it does not give you a portable way to pass data structures between Perl and C programs (which is bound to happen when you call XS extensions or the Perl function "syscall"), or when you read or write binary files. What you need in that case are template codes that depend on what your local C compiler compiles when you code "short" or "unsigned long", for instance. Those codes and their corresponding byte lengths are right here:
signed unsigned byte length in C byte length in Perl
s! S! sizeof(short) $Config{shortsize}
i! I! sizeof(int) $Config{intsize}
l! L! sizeof(long) $Config{longsize}
q! Q! sizeof(long long) $Config{longlongsize}
Since the C standard leaves so much leeway about the relative sizes of these data types, actual values may vary β which is exactly why the values are given as expressions in C and Perl. (If you wanna use values from %Config in your program you have to import it with "use Config".) π
And heads up: the "i!" and "I!" codes aren't different from "i" and "I" β they're just tolerated for completeness' sake.
π₯ Unpacking a Stack Frame
Requesting a particular byte ordering may be necessary when you're working with binary data coming from some specific architecture while your program could run on a totally different system. Example time: assume you have 24 bytes containing a stack frame as it happens on an Intel 8086:
+---------+ +----+----+ +---------+
TOS: | IP | TOS+4:| FL | FH | FLAGS TOS+14:| SI |
+---------+ +----+----+ +---------+
| CS | | AL | AH | AX | DI |
+---------+ +----+----+ +---------+
| BL | BH | BX | BP |
+----+----+ +---------+
| CL | CH | CX | DS |
+----+----+ +---------+
| DL | DH | DX | ES |
+----+----+ +---------+
First thing we clock: this time-honored 16-bit CPU uses little-endian order, which is why the low order byte sits at the lower address. To unpack such an (unsigned) short we gotta use code "v". A repeat count unpacks all 12 shorts:
my( $ip, $cs, $flags, $ax, $bx, $cx, $dx, $si, $di, $bp, $ds, $es ) =
unpack( 'v12', $frame );
Alternatively, we could've used "C" to unpack the individually accessible byte registers FL, FH, AL, AH, etc.:
my( $fl, $fh, $al, $ah, $bl, $bh, $cl, $ch, $dl, $dh ) =
unpack( 'C10', substr( $frame, 4, 10 ) );
And it would be so nice if we could do this in one fell swoop β unpack a short, back up a little, then unpack 2 bytes. Since Perl is nice, it proffers the template code "X" to back up one byte. Putting it all together, we may now write:
my( $ip, $cs,
$flags,$fl,$fh,
$ax,$al,$ah, $bx,$bl,$bh, $cx,$cl,$ch, $dx,$dl,$dh,
$si, $di, $bp, $ds, $es ) =
unpack( 'v2' . ('vXXCC' x 5) . 'v5', $frame );
(The clumsy construction of the template can be avoided β just read on! π§)
We've taken some pains to construct the template so it matches the contents of our frame buffer. Otherwise we'd either get undefined values, or "unpack" couldn't unpack all. And if "pack" runs out of items, it will supply null strings β which get coerced into zeroes whenever the pack code says so.
π How to Eat an Egg on a Net
The pack code for big-endian (high order byte at the lowest address) is "n" for 16 bit and "N" for 32 bit integers. Use these codes if you know your data comes from a compliant architecture β but, surprisingly enough, you should also use these pack codes when you exchange binary data across the network with some system you know next to nothing about. The simple reason: this order has been chosen as the network order, and all standard-fearing programs ought to follow this convention. (Which 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:
my $buf = pack( 'N', length( $msg ) ) . $msg;
or even:
my $buf = pack( 'NA*', length( $msg ), $msg );
and pass $buf 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 "Lengths and Widths" before you really code this! β οΈ)
π¦ Byte-order modifiers
In the previous sections we learned how to use "n", "N", "v" and "V" to pack and unpack integers with big- or little-endian byte-order. Nice, but still kinda limited, because it leaves out all kinds of signed integers and 64-bit integers. Like, if you wanted to unpack a sequence of signed big-endian 16-bit integers in a platform-independent way, you'd have to write:
my @data = unpack 's*', pack 'S*', unpack 'n*', $buf;
Ugly. π But as of Perl 5.9.2, there's a much nicer way to express your desire for a certain byte-order: the ">" and "<" modifiers. ">" is the big-endian modifier, and "<" is the little-endian modifier. Using them, we could rewrite that code as:
my @data = unpack 's>*', $buf;
See how the "big end" of the arrow touches the "s"? That's a cute lil mnemonic for remembering ">" is the big-endian modifier. Same obviously works for "<", where the "little end" touches the code. π
You'll probably find these modifiers even more useful if you have to deal with big- or little-endian C structures. Be sure to read "Packing and Unpacking C Structures" for more on that.
π Floating point Numbers
For packing floating point numbers you've got a choice between the pack codes "f", "d", "F" and "D". "f" and "d" pack into (or unpack from) single-precision or double-precision representation as provided by your system. And if your system supports it, "D" can be used to pack and unpack ("long double") values, which can offer even more resolution than "f" or "d". Note that there are different long double formats.
"F" packs an "NV", which is the floating point type Perl uses internally.
And ngl: 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 text representation β possibly using the hexadecimal float format (avoiding the decimal conversion loss) β unless you're absolutely sure what's on the other end of the line. And for the even more adventuresome? You can use the byte-order modifiers from the previous section on floating point codes too. β¨
π Exotic Templates π
ok so now we get to the weird ones. the exotic templates. the ones that are giving main character energy and nobody knows what to do with them. bestie, buckle in. π¦
π Bit Strings π
Bits are literally the atoms of the memory world, fr fr β smallest thing there is. Access to individual bits may have to be used either as a last resort or because it's just the most convenient way to handle your data. no judgement, do what works.
Bit string (un)packing converts between strings containing a series of 0 and 1 characters, and a sequence of bytes each containing a group of 8 bits. Almost as simple as it sounds β except there are two ways the contents of a byte may be written as a bit string, and that's where the drama lives. look at this annotated byte, she's stunning:
7 6 5 4 3 2 1 0
+-----------------+
| 1 0 0 0 1 1 0 0 |
+-----------------+
MSB LSB
It's egg-eating all over again π₯: some people think that as a bit string this should be written "10001100", i.e. beginning with the most significant bit, and others insist on "00110001". well, Perl isn't biased, so that's why we have two bit string codes:
$byte = pack( 'B8', '10001100' ); # start with MSB
$byte = pack( 'b8', '00110001' ); # start with LSB
okay important: it is not possible to pack or unpack bit fields β just integral bytes. pack 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 actually want bit fields, there's vec in perlfunc. Or you could implement bit field handling at the character string level, using split, substr, and concatenation on unpacked bit strings. your call, bestie. π§)
To illustrate unpacking for bit strings, we'll decompose a simple status register (a - stands for a "reserved" bit):
+-----------------+-----------------+
| S Z - A - P - C | - - - - O D I T |
+-----------------+-----------------+
MSB LSB MSB LSB
Converting these two bytes to a string can be done with the unpack template 'b16'. To obtain the individual bit values from the bit string we use "split" with the "empty" separator pattern which dissects into individual characters. Bit values from the "reserved" positions are simply assigned to "undef", a convenient notation for "I don't care where this goes" β iconic honestly:
($carry, undef, $parity, undef, $auxcarry, undef, $zero, $sign,
$trace, $interrupt, $direction, $overflow) =
split( //, unpack( 'b16', $status ) );
We could have used an unpack template 'b12' just as well, since the last 4 bits can be ignored anyway. slay. β¨
π Uuencoding π
Another odd-man-out in the template alphabet is "u", which packs a "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, okay:
- 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
60and garnish them in front with the original byte count (incremented by0x20) and a"\n"at the end.
the "pack" chef will prepare this for you, Γ la minute, when you select pack code "u" on the menu π©βπ³:
my $uubuf = pack( 'u', $bindat );
A repeat count after "u" 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. "unpack" simply ignores the repeat count. not me noticing that. π
π₯ Doing Sums π₯
An even stranger template code is "%"<number>. First, because it's used as a prefix to some other template code. Second, because it cannot be used in "pack" at all. And third, in "unpack", it doesn't return the data as defined by the template code it precedes. Instead it'll give you an integer of number bits that is computed from the data value by doing sums. for numeric unpack codes, no big feat is achieved:
my $buf = pack( 'iii', 100, 20, 3 );
print unpack( '%32i3', $buf ), "\n"; # prints 123
For string values, "%" returns the sum of the byte values, saving you the trouble of a sum loop with "substr" and "ord":
print unpack( '%32A*', "\x01\x10" ), "\n"; # prints 17
Although the "%" 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. it's giving "close enough" and not "cryptographically secure," bestie. π
In connection with "b" or "B", "%" simply adds bits, and this can be put to good use to count set bits efficiently:
my $bitcount = unpack( '%32b*', $mask );
And an even parity bit can be determined like this:
my $evenparity = unpack( '%1b*', $mask );
πΈ Unicode πΈ
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 <https://www.unicode.org/> for a look at some of them β my personal favourites are Telugu and Kannada. π«Ά)
The Unicode character sets associate 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.
Perl uses UTF-8, internally, for most Unicode strings. π
So what has this got to do with "pack"? Well, if you want to compose a Unicode string (that is internally encoded as UTF-8), you can do so by using template code "U". As an example, let's produce the Euro currency symbol (code number 0x20AC):
$UTF8{Euro} = pack( 'U', 0x20AC );
# Equivalent to: $UTF8{Euro} = "\x{20ac}";
Inspecting $UTF8{Euro} shows that it contains 3 bytes: "\xe2\x82\xac". However, it contains only 1 character, number 0x20AC. The round trip can be completed with "unpack":
$Unicode{Euro} = unpack( 'U', $UTF8{Euro} );
Unpacking using the "U" template code also works on UTF-8 encoded byte strings.
Usually you'll want to pack or unpack UTF-8 strings:
# pack and unpack the Hebrew alphabet
my $alefbet = pack( 'U*', 0x05d0..0x05ea );
my @hebrew = unpack( 'U*', $utf );
Please note: in the general case, you're better off using"Encode::decode('UTF-8', $utf)"to decode a UTF-8 encoded byte string to a Perl Unicode string, and"Encode::encode('UTF-8', $str)"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. π«Ά
π¦ Another Portable Binary Encoding π¦
The pack code "w" has been added to support a portable binary data encoding scheme that goes way beyond simple integers. (Details can be found at <https://github.com/mworks-project/mw_scarab/blob/master/Scarab-0.1.00d19/doc/binary-serialization.txt>, 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. π
my $berbuf = pack( 'w*', 1, 128, 128+1, 128*128+127 );
A hex dump of $berbuf, with spaces inserted at the right places, shows 01 8100 8101 81807F. Since the last byte is always less than 128, "unpack" knows where to stop. she just knows. π
β Template Grouping β
Prior to Perl 5.8, repetitions of templates had to be made by "x"-multiplication of template strings. Now there is a better way, as we may use the pack codes "(" and ")" combined with a repeat count. The "unpack" template from the Stack Frame example can simply be written like this:
unpack( 'v2 (vXXCC)5 v5', $frame )
Let's explore this feature a little more. We'll begin with the equivalent of
join( '', map( substr( $_, 0, 1 ), @str ) )
which returns a string consisting of the first character from each string. Using pack, we can write
pack( '(A)'.@str, @str )
or, because a repeat count "*" means "repeat as often as required", simply
pack( '(A)*', @str )
(Note that the template "A*" would only have packed $str[0] in full length.) π
To pack dates stored as triplets ( day, month, year ) in an array @dates into a sequence of byte, byte, short integer we can write
$pd = pack( '(CCS)*', map( @$_, @dates ) );
To swap pairs of characters in a string (with even length) one could use several techniques. First, let's use "x" and "X" to skip forward and back:
$s = pack( '(A)*', unpack( '(xAXXAx)*', $s ) );
We can also use "@" to jump to an offset, with 0 being the position where we were when the last "(" was encountered:
$s = pack( '(A)*', unpack( '(@1A @0A @2)*', $s ) );
Finally, there is also an entirely different approach by unpacking big endian shorts and packing them in the reverse byte order:
$s = pack( '(v)*', unpack( '(n)*', $s );
β¨ Lengths and Widths β¨
π String Lengths π
So in the section before this one we saw a network message that was constructed by prefixing the binary message length to the actual message. And bestie, packing a length followed by so many bytes of data is a frequently used recipe, because appending a null byte literally won't work if a null byte may be part of the data. π Here's 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:
my $msg = pack( 'Z*Z*CA*', $src, $dst, length( $sm ), $sm );
Unpacking this message can be done with the same template, no cap:
( $src, $dst, $len, $sm ) = unpack( 'Z*Z*CA*', $msg );
But there's a subtle trap lurking in the offing, and it is sneaky π: adding another field after the Short Message (in variable $sm) is all right when packing, but this cannot be unpacked naively:
# pack a message
my $msg = pack( 'Z*Z*CA*C', $src, $dst, length( $sm ), $sm, $prio );
# unpack fails - $prio remains undefined!
( $src, $dst, $len, $sm, $prio ) = unpack( 'Z*Z*CA*C', $msg );
The pack code A* gobbles up all remaining bytes, and $prio remains undefined! π Before we let disappointment dampen the morale, though: Perl's got the trump card to make this trick too, just a little further up the sleeve. Watch this:
# pack a message: ASCIIZ, ASCIIZ, length/string, byte
my $msg = pack( 'Z* Z* C/A* C', $src, $dst, $sm, $prio );
# unpack
( $src, $dst, $sm, $prio ) = unpack( 'Z* Z* C/A* C', $msg );
Combining two pack codes with a slash ("/") associates them with a single value from the argument list. In pack, 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 length call, but it is in unpack 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 a*, A* or Z*, Perl won't let you. Periodt. π«
The pack code preceding / may be anything that's fit to represent a number: all the numeric binary pack codes, and even text codes such as A4 or Z*:
# pack/unpack a string preceded by its length in ASCII
my $buf = pack( 'A4/A*', "Humpty-Dumpty" );
# unpack $buf: '13 Humpty-Dumpty'
my $txt = unpack( 'A4/A*', $buf );
"/" is not implemented in Perls before 5.6, so if your code is required to work on ancient Perls you'll need to unpack( 'Z* Z* C') to get the length, then use it to make a new unpack string. For example
# pack a message: ASCIIZ, ASCIIZ, length, string, byte
# (5.005 compatible)
my $msg = pack( 'Z* Z* C A* C', $src, $dst, length $sm, $sm, $prio );
# unpack
( undef, undef, $len) = unpack( 'Z* Z* C', $msg );
($src, $dst, $sm, $prio) = unpack ( "Z* Z* x A$len C", $msg );
But that second unpack is rushing ahead, bestie. It isn't using a simple literal string for the template. So maybe we should introduce...
π¦ Dynamic Templates π¦
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, ()* 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 "=" between the name and the value, followed by an additional delimiting null byte. Here's how:
my $env = pack( '(A*A*Z*)' . keys( %Env ) . 'C',
map( { ( $_, '=', $Env{$_} ) } keys( %Env ) ), 0 );
Let's examine the cogs of this byte mill, one by one, because honestly the way it works is so satisfying. There's the map call, creating the items we intend to stuff into the $env buffer: to each key (in $_) it adds the "=" separator and the hash entry value. Each triplet is packed with the template code sequence A*A*Z* that is repeated according to the number of keys. (Yes, that's what the keys function returns in scalar context.) To get the very last null byte, we add a 0 at the end of the pack list, to be packed with C. (Attentive readers may have noticed that we could have omitted the 0.) π
For the reverse operation, we'll have to determine the number of items in the buffer before we can let unpack rip it apart:
my $n = $env =~ tr/\0// - 1;
my %env = map( split( /=/, $_ ), unpack( "(Z*)$n", $env ) );
The tr counts the null bytes. The unpack call returns a list of name-value pairs each of which is taken apart in the map block.
πΈ Counting Repetitions πΈ
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:
my $env = pack( 'S(S/A* S/A*)*', scalar keys( %Env ), %Env );
This simplifies the reverse operation as the number of repetitions can be unpacked with the / code:
my %env = unpack( 'S/(S/A* S/A*)', $env );
Note that this is one of the rare cases where you cannot use the same template for pack and unpack because pack can't determine a repeat count for a ()-group. The betrayal π
π Intel HEX π
Intel HEX is a file format for representing binary data, mostly for programming various chips, as a text file. (See https://en.wikipedia.org/wiki/.hex for a detailed description, and https://en.wikipedia.org/wiki/SREC_(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 n (8 bit), an address (16 bit, big endian), a record type (8 bit), n data bytes and a checksum (8 bit) computed as the least significant byte of the two's complement sum of the preceding bytes. Example: ":0300300002337A1E".
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 pack call to convert everything to binary:
my $binrec = pack( 'H*', substr( $hexrec, 1 ) );
The resulting byte sequence is most convenient for checking the checksum. Don't slow your program down with a for loop adding the ord values of this string's bytes β the unpack code % is the thing to use for computing the 8-bit sum of all bytes, which must be equal to zero:
die unless unpack( "%8C*", $binrec ) == 0;
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 x and X come to the rescue, as they permit jumping back and forth in the string to unpack.
my( $addr, $type, $data ) = unpack( "x n C X4 C x3 /a", $bin );
Code x skips a byte, since we don't need the count yet. Code n takes care of the 16-bit big-endian integer address, and C unpacks the record type. Being at offset 4, where the data begins, we need the count. X4 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. Iconic. π
π₯ Packing and Unpacking C Structures π₯
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. π
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 Convert::Binary::C. 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.
π The Alignment Pit π
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?)). π
To see how this affects pack and unpack, we'll compare these two C structures:
typedef struct {
char c1;
short s;
char c2;
long l;
} gappy_t;
typedef struct {
long l;
short s;
char c1;
char c2;
} dense_t;
Typically, a C compiler allocates 12 bytes to a gappy_t variable, but requires only 8 bytes for a dense_t. After investigating this further, we can draw memory maps, showing where the extra 4 bytes are hidden:
0 +4 +8 +12
+--+--+--+--+--+--+--+--+--+--+--+--+
|c1|xx| s |c2|xx|xx|xx| l | xx = fill byte
+--+--+--+--+--+--+--+--+--+--+--+--+
gappy_t
0 +4 +8
+--+--+--+--+--+--+--+--+
| l | h |c1|c2|
+--+--+--+--+--+--+--+--+
dense_t
And that's where the first quirk strikes: pack and unpack templates have to be stuffed with x codes to get those extra fill bytes. π«
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 union where the amount of fill bytes cannot be derived from the alignment of the next item alone.
OK, so let's bite the bullet. Here's one way to get the alignment right by inserting template codes x, which don't take a corresponding item from the list:
my $gappy = pack( 'cxs cxxx l!', $c1, $s, $c2, $l );
okay so bestie, peep the ! sittin' right after that l π β that's us saying "pack a long integer exactly the way our C compiler compiles it." And even with the !, this only works on platforms where the compiler aligns things the way we just said. And somewhere out there, somebody's got a platform where it justβ¦ doesn't. π [Probably a Cray, where shorts, ints and longs are all 8 bytes. :-)]
Counting bytes and babysitting alignments across long structures is such a drag. Isn't there a way to build the template with a simple program instead of by hand? GIRL YES. Here's a C program that does the trick:
#include <stdio.h>
#include <stddef.h>
typedef struct {
char fc1;
short fs;
char fc2;
long fl;
} gappy_t;
#define Pt(struct,field,tchar) \
printf( "@%d%s ", offsetof(struct,field), # tchar );
int main() {
Pt( gappy_t, fc1, c );
Pt( gappy_t, fs, s! );
Pt( gappy_t, fc2, c );
Pt( gappy_t, fl, l! );
printf( "\n" );
}
The line it spits out can be dropped straight in as a template for a pack or unpack call:
my $gappy = pack( '@0c @2s! @4c @8l!', $c1, $s, $c2, $l );
Gee, yet another template code β as if we didn't already have plenty. π But @ literally saves our whole day, because it lets us specify the offset from the beginning of the pack buffer to the next item. That's exactly the value the offsetof macro (defined in <stddef.h>) hands back when you give it a struct type and one of its field names (member-designator in C standardese).
Now, neither using offsets nor sprinkling x's in there to bridge the gaps is actually satisfying. (Just imagine what happens if the structure changes. π) What we really need is a way to say "skip as many bytes as required to the next multiple of N". In fluent templates, you say that with x!N, where N is the value you want. Here's the next version of our struct packing:
my $gappy = pack( 'c x!2 s c x!4 l!', $c1, $s, $c2, $l );
That's definitely better, but we still have to know how long every integer is, and portability is still a million miles away. Instead of 2, for instance, we wanna say "however long a short is". And we can totally do that by wrapping the appropriate pack code in brackets: [s]. So here's the very best we can do:
my $gappy = pack( 'c x![s] s c x![l!] l!', $c1, $s, $c2, $l );
β¨ Dealing with Endian-ness β¨
Now imagine we want to pack data for a machine with a different byte-order. First we gotta figure out how big the data types on the target machine actually are. Let's assume the longs are 32 bits wide and the shorts are 16 bits wide. Then you can rewrite the template as:
my $gappy = pack( 'c x![s] s c x![l] l', $c1, $s, $c2, $l );
If the target machine is little-endian, we could write:
my $gappy = pack( 'c x![s] s< c x![l] l<', $c1, $s, $c2, $l );
That forces the short and the long members to be little-endian, and it's just fine if you don't have too many struct members. But we could also slap the byte-order modifier onto a whole group and write this:
my $gappy = pack( '( c x![s] s c x![l] l )<', $c1, $s, $c2, $l );
Not as short as before, but it makes it so much more obvious that we intend little-endian byte-order for an entire group, not just for individual template codes. It's also more readable and way easier to maintain. iconic behavior tbh.
π«Ά Alignment, Take 2 π«Ά
I'm afraid we are not done with the alignment drama yet, bestie. The hydra pops another ugly head the second you pack arrays of structures:
typedef struct {
short count;
char glyph;
} cell_t;
typedef cell_t buffer_t[BUFLEN];
So where's the catch? Padding isn't required before the first field count, and it isn't required between that and the next field glyph either β so why can't we just pack it like this?
# something goes wrong here:
pack( 's!a' x @buffer,
map{ ( $_->{count}, $_->{glyph} ) } @buffer );
Because this packs 3*@buffer bytes, but it turns out the size of buffer_t is four times BUFLEN! π The moral of the story: the required alignment of a structure or array gets propagated up to the next higher level, where we have to consider padding at the end of each component too. So the correct template is:
pack( 's!ax' x @buffer,
map{ ( $_->{count}, $_->{glyph} ) } @buffer );
π Alignment, Take 3 π
And even if you take all of the above into account, ANSI still lets this:
typedef struct {
char foo[2];
} foo_t;
vary in size. The alignment constraint of the structure can be greater than any of its elements. [And if you think that doesn't affect anything common, go ahead and dismember the next cellphone you see. π± Many have ARM cores, and the ARM structure rules make sizeof (foo_t) == 4.]
π Pointers for How to Use Them π
This section's title is hinting at 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, void * value, you cannot simply take a reference to a Perl variable. (Sure, that value is definitely a memory address β but it is not the address where the variable's contents are stored.)
Template code P promises to pack a "pointer to a fixed length string". Isn't that what we want? Let's try:
# allocate some storage and pack a pointer to it
my $memory = "\x00" x $size;
my $memptr = pack( 'P', $memory );
But wait β doesn't pack just return a sequence of bytes? How are we supposed to hand this string of bytes to some C code that's expecting a pointer, which is, at the end of the day, nothing but a number? The answer is simple: we have to obtain the numeric address from the bytes that pack returned.
my $ptr = unpack( 'L!', $memptr );
Obviously this assumes you can 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 do 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:
ssize_t read(int fd, void *buf, size_t count);
After reading perlfunc to see how to use syscall, we can write this Perl function that copies a file to standard output:
require 'syscall.ph'; # run h2ph to generate this file
sub cat($){
my $path = shift();
my $size = -s $path;
my $memory = "\x00" x $size; # allocate some memory
my $ptr = unpack( 'L', pack( 'P', $memory ) );
open( F, $path ) || die( "$path: cannot open ($!)\n" );
my $fd = fileno(F);
my $res = syscall( &SYS_read, fileno(F), $ptr, $size );
print $memory;
close( F );
}
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 syscall does not require you to construct pointers in this roundabout way. You simply pass a string variable, and Perl forwards the address.)
So how does unpack with P work? Imagine some pointer in the buffer that's about to be unpacked: if it isn't the null pointer (which will smartly produce the undef 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 on you to specify the actual size as an explicit length after P.
my $mem = "abcdefghijklmn";
print unpack( 'P5', pack( 'P', $mem ) ); # prints "abcde"
As a consequence, pack ignores any number or * after P.
Now that we've seen P at work, we might as well give p a whirl. Why do we even need a second template code for packing pointers? The answer lives behind the simple fact that an unpack with p promises a null-terminated string starting at the address taken from the buffer β and that implies a length for the data item being returned:
my $buf = pack( 'p', "abc\x00efhijklmn" );
print unpack( 'p', $buf ); # prints "abc"
Albeit this is apt to be confusing: because the length is implied by the string's length, a number after pack code p is a repeat count, not a length like it is after P.
Using pack(..., $x) with P or p to get the address where $x is actually stored must be used with circumspection. Perl's internal machinery treats the relation between a variable and that address as its very own private business and doesn't really care that we've obtained a copy. Therefore:
- Do not use
packwithporPto obtain the address of a variable that's bound to go out of scope (and thereby free its memory) before you're done using the memory at that address. - 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.
- Don't think you can get the address of a Perl variable when it's stored as an integer or double number!
pack('P', $x)will force the variable's internal representation to string, just as if you had written something like$x .= ''.
It is safe, however, to P- or p-pack a string literal, because Perl simply allocates an anonymous variable. π«Ά
π Pack Recipes π
Here's a whole lil collection of (possibly) useful canned recipes for pack and unpack:
# Convert IP address for socket functions
pack( "C4", split /\./, "123.4.5.6" );
# Count the bits in a chunk of memory (e.g. a select vector)
unpack( '%32b*', $mask );
# Determine the endianness of your system
$is_little_endian = unpack( 'c', pack( 's', 1 ) );
$is_big_endian = unpack( 'xc', pack( 's', 1 ) );
# Determine the number of bits in a native integer
$bits = unpack( '%32I!', ~0 );
# Prepare argument for the nanosleep system call
my $timespec = pack( 'L!L!', $secs, $nanosecs );
And for a simple memory dump, we unpack some bytes into just as many pairs of hex digits, then use map to handle the traditional spacing β 16 bytes to a line:
my $i;
print map( ++$i % 16 ? "$_ " : "$_\n",
unpack( 'H2' x length( $mem ), $mem ) ),
length( $mem ) % 16 ? "\n" : '';
πͺ Funnies Section πͺ
# Pulling digits out of nowhere...
print unpack( 'C', pack( 'x' ) ),
unpack( '%B*', pack( 'A' ) ),
unpack( 'H', pack( 'A' ) ),
unpack( 'A', unpack( 'C', pack( 'A' ) ) ), "\n";
# One for the road ;-)
my $advice = pack( 'all u can in a van' );
not the pack( 'all u can in a van' ) ππ it's giving unhinged and I respect it.
π Authors π
Simon Cozens and Wolfgang Laun. legends, fr fr. π
and that's the whole page, bestie!! this lil masterpiece is from perl v5.42.3, dated 2026-08-03, and it lives in section PERLPACKTUT(1). go forth and pack responsibly πβ¨π
π¦ where this page comes from
- fedora 43: perl-doc 5.42.3-524.fc43 Β· (GPL-1.0-or-later OR Artistic-1.0-Perl) AND Unicode-3.0 AND LicenseRef-Fedora-UltraPermissive
- fedora 44: perl-doc 5.42.3-525.fc44 Β· (GPL-1.0-or-later OR Artistic-1.0-Perl) AND Unicode-3.0 AND LicenseRef-Fedora-UltraPermissive
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms