- 论坛徽章:
- 0
|
本帖最后由 zhuyubei 于 2012-08-16 20:04 编辑
今天继续Recipe1.1的剩余部分。使用unpack来获取子字符串。unpack会把字符串当成字节流来处理。
unpack需要一个格式化字符串和输入字符串。而格式化字符串由可识别的关键字符和其需要的数量组成。比如关键字符x代表跳过字节,A表示获取字节- x: skip, X: backward skip A: get byte
复制代码 看个例子。这个例子是先跳过6个字节,再读取6个字节。这样$sUnppackStr的得就是or not
- $sString = "To be or not to be";
- my $sUnpackStr = unpack( "x6 A6 ", $sString ); #skip 6 bytes, then get 6 bytes
- print "After unpack: $sUnpackStr\n";
复制代码 这样通过格式化字符串,可以让unpack一次返回多个子字符串。标量环境下,返回多个子字符串的话,标量会接受第一个子字符串- # Get multiple substrings at a time
- # X5: backward skip bytes, A*: Get rest of the bytes
- my ( $sStr1, $sStr2, $sStr3 ) = unpack( "x6 A2 X5 A2 A*", $sString );
- print "Multiple substrings: [$sStr1], [$sStr2], [$sStr3]\n";
- # scalar context uses the first value
- my ( $sScalar ) = unpack( "x6 A2 X5 A2 A*", $sString );
- print "Scalar context: [$sScalar]\n";
复制代码 另外Perl的unpack有个很强大的功能,就是使用在格式化字符串里使用A*, 可以让unpack返回从当前字节位置到字符串结尾的子字符串。。
这个格式化字符串的意思是跳过6字节,读取2个字节,再读取字符串里剩余的字节。
而Python则不支持这种格式化方式来获取到结尾的子字符串
|
|