Instead of removing parsed chars from the strings, I'd use pos to keep track of where you are in the string. That way, you can intermix the use regexps and substr to extract data from the packed string.

for ($packed) { # alias $_ = $packed; pos = 0; /\G (.) /xgc or die; my $count = unpack('C', $1); for my $i (1..$count) { /\G (.) /xgc or die; # Extract data using a re my $length = unpack('C', $1); my $str = substr($_, pos, $length); # Extract data using substr pos($_) += $length; # Don't forget to upd pos push @strings, $str; } # Make sure there's nothing extra at the end. /\G \z /xgc or die; }

Another advantage to this method is that you can break your parser down into multiple functions.

sub extract_string { /\G (.) /xgc or die; my $length = unpack('C', $1); my $str = substr($_, pos, $length); pos($_) += $length; return $str; } sub parse { for ($_[0]) { # alias $_ = $_[0]; pos = 0; /\G (.) /xgc or die; my $count = unpack('C', $1); my @strings; for my $i (1..$count) { push @strings, extract_string(); } # Make sure there's nothing extra at the end. /\G \z /xgc or die; return @strings; } } my @strings = parse($packed);

The final advantage is backtracking. Since the the string isn't being destroyed, parts of it can be re-parsed.

Update: Added advantages and second snippet.


In reply to Re: Faster way to parse binary stream by ikegami
in thread Faster way to parse binary stream 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.