unpack
unpackTEMPLATE,EXPR
This function does the reverse of pack: it expands a string
(EXPR) representing a data structure into a
list of values according to the TEMPLATE and
returns those values. In scalar context, it can be used to unpack a
single value. The TEMPLATE here has much the
same format as it has in the pack
function—it specifies the order and type of the values to be unpacked.
See pack for a detailed description
of TEMPLATE. An invalid element in the
TEMPLATE, or an attempt to move outside the
string with the x, X, or @
formats, raises an exception.
The string is broken into chunks described by the
TEMPLATE. Each chunk is separately converted
to a value. Typically, the bytes of the string either are the result of
a pack or represent a C structure of
some kind.
If the repeat count of a field is larger than the remainder of the
input string allows, the repeat count is silently decreased. (Normally,
you’d use a repeat count of * here,
anyway.) If the input string is longer than what
TEMPLATE describes, the rest of the string is
ignored.
The unpack function is also
useful for plain text data, not just binary data. Imagine that you had a
data file that contained records that looked like this:
2009 The Graveyard Book Neil Gaiman 2008 The Yiddish Policemen’s Union Michael Chabon 2007 Rainbows End Vernor Vinge 2006 Spin Robert Charles Wilson 2005 Jonathan Strange & Mr Norrell Susanna Clarke 2004 Paladin of Souls Lois McMaster Bujold 2003 Hominids Robert J. Sawyer 2002 American ...
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