如何在 Perl 中获取已打包项目的数量而不实际拆包?
我有一个 packed
值的字符串,它是使用以下内容按顺序创建的:
while (...) {
...
$packed .= pack( 'L', $val );
}
在另一个程序中,在加载 $packed
后,我希望找出实际有多少个值打包。我知道解压后该怎么做:
my @vals = unpack( 'L*', $packed );
print scalar(@vals);
但这真的有必要吗?如果我只关心值的数量,我可以做得更好并跳过解包
吗?
I have a string of pack
ed values which was created sequentially using something like:
while (...) {
...
$packed .= pack( 'L', $val );
}
In another program, after I load $packed
, I wish to find out how many values were actually packed. I know how to do that after unpack
ing:
my @vals = unpack( 'L*', $packed );
print scalar(@vals);
But is it really necessary? If I only care about the number of values, can I do better and skip the unpack
ing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于您知道打包值的大小(
L
是一个无符号 32 位 int,或 4 个字节),只需将长度除以大小即可:如果您不想对大小进行硬编码,您还可以打包一个样本值来计算它。 (请注意,Perl 的编译时常量折叠不适用于
pack
,至少不适用于 5.10.1,因此您只需执行该计算一次。)Since you know the size of a packed value (
L
is an unsigned 32-bit int, or 4 bytes), just divide the length by the size:If you don't want to hard code the size, you could also pack a sample value to calculate it. (Note that Perl's compile-time constant folding doesn't work with
pack
, at least not with 5.10.1, so you'd want to do that calculation only once.)由于
L
只是 32 位值的组,因此您可以简单地计算字节数并除以 4。Since
L
is merely groups of 32 bit values, you can simply count the number of bytes and divide by 4.检查
LLength
是否确实是常量:Check if
LLength
is really constant: