pack
packTEMPLATE,LIST
This function takes a LIST of
ordinary Perl values, converts them into a string of bytes according to
the TEMPLATE, and returns this string. The
argument list will be padded or truncated as necessary. That is, if you
provide fewer arguments than the TEMPLATE
requires, pack assumes additional
null arguments. If you provide more arguments than the
TEMPLATE requires, the extra arguments are
ignored. Unrecognized format elements in
TEMPLATE will raise an exception.
The template describes the structure of the string as a sequence
of fields. Each field is represented by a single character that
describes the type of the value and its encoding. For instance, a format
character of N specifies an unsigned
four-byte integer in big-endian byte order.
Fields are packed in the order given in the template. For example, to pack an unsigned one-byte integer and a single-precision floating-point value into a string, you’d say:
$string = pack("Cf", 244, 3.14);The first byte of the returned string has the value 244. The remaining bytes are the encoding of 3.14 as a single-precision float. The particular encoding of the floating-point number depends on your computer’s hardware.
Some important things to consider when packing are:
The type of data (such as integer or float or string)
The range of values (such as whether your integers will fit into one, two, four, or maybe even eight bytes; or whether you’re packing 8-bit or Unicode characters)
Whether your integers are signed or unsigned ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access