in reply to Problems Getting the Template Correct when Using unpack()

Your last format is very close to correct. Because the result $data is a string, the format field that corresponds to it must be an 'A', not a 'C'.
#my @formats = ( "C*", "C8a6C*", "C8a*", "C8a6C33C1"); my @formats = ( "C8A6A33C1" );
Bill

Replies are listed 'Best First'.
Re^2: Problems Getting the Template Correct when Using unpack()
by ozboomer (Friar) on Oct 10, 2017 at 22:37 UTC

    By way of some more clarification, BTW...

    From reading pack, there was something about how 'A' strips whitespace, etc and 'a' doesn't do that when using unpack. For no particular reason, I wanted to retain the entire field, hence the usage of 'a' in the template.

      'A' strips whitespace, etc and 'a' doesn't do that

      True, but I think BillKSmith's point was that you were using 'C' instead of 'a'. From pack:

      a A string with arbitrary binary data, will be null padded. A A text (ASCII) string, will be space padded. Z A null-terminated (ASCIZ) string, will be null padded. C An unsigned char (octet) value.

      Here's the difference:

      use Data::Dump; my $data = "\x01\x02\x03\x20\x00"; dd unpack 'C*', $data; # prints (1, 2, 3, 32, 0) dd unpack 'a*', $data; # prints "\1\2\3 \0" dd unpack 'A*', $data; # prints "\1\2\3" dd unpack 'Z*', $data; # prints "\1\2\3 " dd unpack 'Z*', $data."X "; # prints "\1\2\3 " dd unpack 'A*', $data."X "; # prints "\1\2\3 \0X" dd unpack 'a*', $data."X "; # prints "\1\2\3 \0X "

      So if you want to retain all of the binary data as a string for further unpacking, the 'a' template is the way to go. 'C' will split that string into its individual bytes and return those values.

      Update: Added the second 'A*' example.