What the heck is pack?

The internal commands pack and unpack have been the source of much confusion, therefore, I will shortly present typical scenarios when to use pack and unpack.

The following example unpacks a string to its hexadecimal representation. the command reads lines from stdin and returns the unpack’d value. The trailing 0a denotes the new line character as shown in the second line which is produces by providing a single new line character.

perl -ne "print unpack 'H*', $_"

Similarily to the example above, the following code demonstrated how to retrieve the binary representation of the input. In this case, the new line character is represented by 00001010.

perl -ne "print unpack 'B*', $_"

To obtain the original representation of the converted string, use the following code. The hexadecimal string can easily be converted by using H* instead of B*.

perl -ne "print pack 'B*', $_"

See also: Performance considerations

Feedback is always welcome! If you'd like to get in touch with me concerning the contents of this article, please use Twitter.