pack Function in Perl

What is pack Function in Perl?


The pack function takes "LIST" of values and converts it into a binary structure using the rules given by the "TEMPLATE".



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:programfilesperlbinperl
print "content-type: text/htmlnn";
$b = pack( "sai", 255, "X", 29 );
print "bits are $bitsn";
@array = unpack( "sai", "$b" );
print "Array $array[0]n";
print "Array $array[1]n";
print "Array $array[2]n";
Result :

ASCII Value of 66 is:: B
The ASCII Values with null values inbetween:: ABCD

In the above pack function example first the ASCII value of "66" is "B" which is printed, then in the second example the list has "ccxxcc", whereas as only four numbers are given, so first the ASCII Value of the first two numbers are printed then the null values are printed twice then the ASCII value of other two numbers are printed.

Ask Questions

Ask Question