pack, unpack

A list of values is packed into a binary structure.

$ret = pack(TEMPLATE, @list);

The TEMPLATE is a sequence of characters that give the order and type of values, as follows:


Table 8.1: pack
A An ascii string, will be space padded.
a An ascii string, will be null padded.
c A signed char value.
C An unsigned char value.
s A signed short value.
S An unsigned short value.
i A signed integer value.
I An unsigned integer value.
l A signed long value.
L An unsigned long value.
n A short in "network" order.
N A long in "network" order.
f A single-precision float in the native format.
d A double-precision float in the native format.
p A pointer to a string.
v A short in "VAX" (little-endian) order.
V A long in "VAX" (little-endian) order.
x A null byte.
X Back up a byte.
@ Null fill to absolute position.
u A uuencoded string.
b A bit string (ascending bit order, like vec()).
B A bit string (descending bit order).
h A hex string (low nybble first).
H A hex string (high nybble first).


Each letter may optionally be followed by a number which gives a repeat count. A $*$ for the repeat count means to use however many items are left.

Examples:

@list = (65,66,67); 
$str = pack("CCC", @list);  # --> "ABC", 'C' -> unsigned char
$str = pack("C3", @list);   # --> "ABC"
$str = pack("C*", @list);   # --> "ABC"
@list = unpack("C*", $str); # --> 65 66 67

$str = pack("ccxxcc", @list); # --> "AB\0\0CD"

$str = pack("s2",1,2); # --> "\1\0\2\0" on little-endian
                       # --> "\0\1\0\2" on big-endian

$str = pack("a4","abcd","x","y","z");   # --> "abcd"

$str = pack("aaaa","abcd","x","y","z"); # --> "axyz"

$str = pack("a14","abcdefg"); # -->"abcdefg\0\0\0\0\0\0\0"

sub bin2dec { return unpack("N", pack("B32", substr("0" x 32 . shift, -32))); }

Unpack does the reverse of pack: it takes a string representing a structure and expands it out into an array value, returning the array value. (In a scalar context, it merely returns the first value produced.)

The TEMPLATE has the same format as in the pack function. Here's a subroutine that does substring:

sub substr 
{
  local($expr,$offset,$len) = @_;
  unpack("x$offset a$len", $expr);
}