From the documentation, pack'ing ...
When used with Z , a * as the repeat count is guaranteed to add a trailing null byte, so the resulting string is always one byte longer than the byte length of the item itself.
And unpack'ing (my boldened text) ...
When unpacking, A strips trailing whitespace and nulls, Z strips everything after the first null, and a returns data with no stripping at all.
Using the 'Z*' template to pack seems to work as described, adding a trailing null to the packed string. However, my reading of the documentation is that a single trailing null will be left in the unpack'ed string. This does not seem to happen.
johngg@shiraz:~/perl > perl -Mstrict -Mwarnings -E ' my $str = q{abc }; my $pck = pack q{Z*}, $str; say sprintf q{%02x}, ord for split m{}, $pck; say q{-} x 5; say sprintf q{%02x}, ord for split m{}, unpack q{Z*}, $pck;' 61 62 63 20 20 00 ----- 61 62 63 20 20
Testing all three templates shows that 'A' and 'a' behave as described.
johngg@shiraz:~/perl > perl -Mstrict -Mwarnings -E ' my $str = q{abc }; my $pck = pack q{a10}, $str; say qq{unpack A*:}; say sprintf q{ %02x}, ord for split m{}, unpack q{A*}, $pck; say qq{unpack Z*:}; say sprintf q{ %02x}, ord for split m{}, unpack q{Z*}, $pck; say qq{unpack a*:}; say sprintf q{ %02x}, ord for split m{}, unpack q{a*}, $pck;' unpack A*: 61 62 63 unpack Z*: 61 62 63 20 20 unpack a*: 61 62 63 20 20 00 00 00 00 00
I have tested this under perl 5.18.2 on Linux and 5.12.4 on Darwin, the documentation is consistent for those versions and the latest 5.24.0. The current behaviour of 'Z' actually suits what I am doing much better than leaving a trailing null so I'm hoping it is the documentation (or my reading of it) that is wrong.
Am I being obtuse or is the documentation out of kilter?
Cheers,
JohnGG
In reply to Behaviour of unpack() with the Z template by johngg
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |