If not for the requirement that the length is sometimes (the OP implies randomly) given as the negative of the true length, this would be simple and probably fairly quick. As ikegami wrote, the trick is to first convert the hex input string to raw binary.

This code works and will probably be somewhat faster than the code in the OP, but will certainly be slower than ikegami's suggestion, could it be used.

C:\@Work\Perl\monks\714341>perl -wMstrict -le "print qq(\noutput:); for (@ARGV) { my $data = pack( 'H*', $_); my $offset = 0; while ($offset < length $data) { my ($kategory, $len) = unpack(qq{x$offset n n}, $data); $len = 65536 - $len if $len > 32767; my $contents = unpack(qq(x$offset x4 A$len), $data); $offset += 4 + $len; printf(qq(%04X, `%s' \n), $kategory, $contents); } print '------'; } " 0001fffd206162 0002000441424344 0001fffd20616200020004414243440005fffc454443 output: 0001, ` ab' ------ 0002, `ABCD' ------ 0001, ` ab' 0002, `ABCD' 0005, `EDC' ------
You might try "\@$offset" in place of the "x$offset"; it might give you a slight speed improvement, but I doubt it. (The backslash escape before the '@' is needed to prevent interpolation as an array in the double-quoted string of the unpack template.)

In reply to Re: pack with count in the data by AnomalousMonk
in thread pack with count in the data by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.