如何在 Perl 中获取已打包项目的数量而不实际拆包?

发布于 2024-09-25 18:48:48 字数 340 浏览 3 评论 0原文

我有一个 packed 值的字符串,它是使用以下内容按顺序创建的:

while (...) {
 ...
 $packed .= pack( 'L', $val );
}

在另一个程序中,在加载 $packed 后,我希望找出实际有多少个值打包。我知道解压后该怎么做:

my @vals = unpack( 'L*', $packed );
print scalar(@vals);

但这真的有必要吗?如果我只关心值的数量,我可以做得更好并跳过解包吗?

I have a string of packed 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 unpacking:

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 unpacking?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

生生漫 2024-10-02 18:48:48

由于您知道打包值的大小(L 是一个无符号 32 位 int,或 4 个字节),只需将长度除以大小即可:

my $count = length($packed) / 4;

如果您不想对大小进行硬编码,您还可以打包一个样本值来计算它。 (请注意,Perl 的编译时常量折叠不适用于 pack,至少不适用于 5.10.1,因此您只需执行该计算一次。)

my $size = length(pack('L', 0));
...
my $count = length($packed) / $size;

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:

my $count = length($packed) / 4;

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.)

my $size = length(pack('L', 0));
...
my $count = length($packed) / $size;
陈甜 2024-10-02 18:48:48

由于 L 只是 32 位值的组,因此您可以简单地计算字节数并除以 4。

Since L is merely groups of 32 bit values, you can simply count the number of bytes and divide by 4.

脱离于你 2024-10-02 18:48:48
use constant LLength => length(pack("L", 0));
...
print length($packed)/LLength;

检查LLength是否确实是常量:

$ perl -MO=Deparse,-d -e'use constant L => length(pack("L", 0));print L, "\n";'
sub L () { 4 }
use constant ("L", length pack("L", 0));
print 4, "\n";
-e syntax OK
use constant LLength => length(pack("L", 0));
...
print length($packed)/LLength;

Check if LLength is really constant:

$ perl -MO=Deparse,-d -e'use constant L => length(pack("L", 0));print L, "\n";'
sub L () { 4 }
use constant ("L", length pack("L", 0));
print 4, "\n";
-e syntax OK
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文