What is pack and unpack in Perl?

The pack and unpack functions in Perl are two functions for transforming data into a user-defined template.

The pack and unpack functions are used to convert data to and from a sequence of bytes. This is useful when accessing data from the network, a file, or I/O.

Pack

The pack function evaluates the data in List and outputs a binary representation of that data according to Expr.

Syntax

pack Expr, List

Parameters

  • Expr: A character that is optionally followed by a number (e.g. A2). Each character defines how the next sequence of bits is to be interpreted, and the number following the character represents how many times the sequence should be repeated.
  • List: The data that is converted into bytes.

Return value

pack returns the bit representation of the data in List, interpreting it according to the rules defined in Expr.

Code

The code below converts the integer 6565 into the ASCII character A. Expr is C, which means that pack should convert the next character to its ASCII representation in bits.

$bits = pack("C", 65);
print "bits are $bits\n";

Unpack

The unpack function evaluates the bitstream in List and interprets it according to Expr before outputting it.

Syntax

pack Expr, List

Parameters

  • Expr: A character that is optionally followed by a number (e.g. A2). Each character defines how the next sequence of bits is to be interpreted, and the number following the character represents how many times the sequence should be repeated.
  • List: The data that is interpreted.

Return value

unpack returns the representation of the bitstream in List according to the rules defined in Expr.

Code

The code below converts the bitstream for ‘A’ into the integer 6565. Expr is c, which means that unpack should convert the next sequence of bits as a signed character.

$var = unpack('c', pack('C', 65));
print "VAR is $var";

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved