johngg has asked for the wisdom of the Perl Monks concerning the following question:
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Behaviour of unpack() with the Z template
by Eily (Monsignor) on Feb 07, 2017 at 18:55 UTC | |
by johngg (Canon) on Feb 08, 2017 at 10:25 UTC | |
by Eily (Monsignor) on Feb 08, 2017 at 15:10 UTC | |
|
Re: Behaviour of unpack() with the Z template
by andal (Hermit) on Feb 08, 2017 at 07:04 UTC | |
by johngg (Canon) on Feb 08, 2017 at 10:45 UTC | |
by andal (Hermit) on Feb 11, 2017 at 10:55 UTC | |
|
Re: Behaviour of unpack() with the Z template
by ikegami (Patriarch) on Feb 08, 2017 at 17:20 UTC | |
|
Re: Behaviour of unpack() with the Z template
by Anonymous Monk on Feb 07, 2017 at 18:11 UTC | |
by johngg (Canon) on Feb 08, 2017 at 10:12 UTC | |
by johngg (Canon) on Feb 07, 2017 at 23:32 UTC |