hexcoder has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

I am struggling to understand the more advanced (un)pack templates, which allow me to describe my data structure.

I have this structure packed in a string $testinput:
  • byte: number of members in each of the following arrays
  • array of bytes
  • array of unsigned shorts
  • another array of unsigned shorts
  • I would like to know, if there is a single unpack template, that uses the first entry not only for sizing the following array, but instead three times for each of them.

    This is what I have tried so far, and I am not really happy with it.
    use strict; use warnings; my $testinput = pack('C/a* a* a*', (pack 'C*', 1, 2), (pack 'v*', 3, 4), (pack 'v*', 5, 6)); print join(',', unpack('C/C* v2 v2', $testinput)), "\n"; # gives "1,2,3,4,5,6" which is ok, # but has the repeat factors for 'v' hardcoded my $repeat = unpack('C', $testinput); print join(',', unpack("C/C* v$repeat v$repeat", $testinput)), "\n"; # gives "1,2,3,4,5,6" which is ok, but uses two steps
    Is it possible to use one call to unpack to expand this string to the values above?

    Thanks in advance, hexcoder