Perl unpack() Function

What is unpack() Function in Perl programming?


The unpack() function is used to convert binary structure into normal perl variables.



In the above syntax unpack() function takes a list as argument.

The following table list the values to be used in templates.
Character Description
a ASCII character string padded with null characters
A ASCII character string padded with spaces
b String of bits, lowest first
B String of bits, highest first
c A signed character (range usually -128 to 127)
C An unsigned character (usually 8 bits)
d A double-precision floating-point number
f A single-precision floating-point number
h Hexadecimal string, lowest digit first
H Hexadecimal string, highest digit first
i A signed integer
I An unsigned integer
l A signed long integer
L An unsigned long integer
n A short integer in network order
N A long integer in network order
p A pointer to a string
s A signed short integer
S An unsigned short integer
u Convert to uuencode format
v A short integer in VAX (little-endian) order
V A long integer in VAX order
x A null byte
X Indicates "go back one byte"
@ Fill with nulls

Example :

#! C:\programfiles\perl\bin\perl
print "content-type: text/html\n\n";
$b = pack( "sai", 255, "T", 30 );
print "Bits are $b\n";
print "<br>";
@array = unpack( "sai", "$b" );
print "Array $array[0]\n";
print "Array $array[1]\n";
print "Array $array[2]\n";

Result :

Bits are T
Array 255 Array T Array 30

In the above example the first the list values are packed using the template "sai", where "s" for signed short integer "a" for ASCII character string padded with null characters, "i" for a signed integer, so the packed values when printed will not have a clear display, to upack the list we need to use the same template and the list stored in a variable, so that all original values are displayed.

Ask Questions

Ask Question