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?
Since you know the size of a packed value (
Lis 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.)