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 函數的使用。