http://www.perlmonks.org?node_id=1034820


in reply to how to unpack a C struct with length array preceding data array

I had to resort to two unpack()'s ... how to do this in one unpack.

Doing this in one statement and with one unpack, if it's even possible (and I don't think it is (Update: but I think wrong: see ig's reply)), might qualify as a neat hack, but it's also a hack which you should then look at, sigh, and set aside in favor of a maintainable two-statement solution. What is the practical advantage of doing this in one statement?

Update: I think I would take a slightly different approach to unpack-ing the final data strings:

>perl -wMstrict -le "my $struct = qq{\x0d\x00\x0b\x00Just Another Perl Hacker}; ;; my @len = unpack 'ss', $struct; print qq{@len}; ;; my @data = unpack qq{(x[s])2 A$len[0] A$len[1]}, $struct; print qq{'$data[0]' '$data[1]'}; " 13 11 'Just Another' 'Perl Hacker'

(Note that  '(x[s])2' could just as well be  'x[s] x[s]'.)