pack EXPR, LIST |
计算该表达式在列表中,包成一个指定的EXPR的二元结构。使用下表中所示的字符格式指定:
每个字符可以被后面可以跟一个数字,指定重复次数的类型被包装的的值。是半字节,字符,或偶数比特,根据该格式。*重复值,为尽可能多的价值保留在LIST中。值可以解压缩与解压缩功能。
例如,A5预期表示五个字母。B32表示,预期32位。为h8表示预期8 nybbles(或4个字节)。P10表示的结构是10个字节长。
包(packed)的版本使用模板来确定它是如何编码的数据列表。
下面是表,它给出在TEMPLATE要使用的值。
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 (ASCII 0) |
试试下面的例子:
#!/usr/bin/perl -w #by www.gitbook.net $bits = pack("c", 65); # prints A, which is ASCII 65. print "bits are $bits\n"; $bits = pack( "x" ); # $bits is now a null chracter. print "bits are $bits\n"; $bits = pack( "sai", 255, "T", 30 ); # creates a seven charcter string on most computers' print "bits are $bits\n"; @array = unpack( "sai", "$bits" ); #Array now contains three elements: 255, T and 30. print "Array $array[0]\n"; print "Array $array[1]\n"; print "Array $array[2]\n";
这将产生以下这些二进制结果:
bits are A bits are bits are �T Array 255 Array T Array 30
请查看Socket编程会话,看看 pack 函数的使用。