Binary Formats

If you’re familiar with more traditional languages, you may have come across the concept of records or struct types. In contrast to sprintf, which is primarily oriented toward human-readable output, the pack and unpack functions are useful for low-level, repetitive conversion and formatting of basic datatypes into (and back out of) string representations of these struct or record types. The two functions share a template language, with minor differences, described in the next section.



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 ...

Get Programming Perl, 4th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.