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


in reply to Re^3: how to unpack a C struct with length array preceding data array
in thread how to unpack a C struct with length array preceding data array

... the absolute positioning solution ... is not really extensible to more than 2 len/data pairs.

I disagree, with a potential caveat dependent on the exact meaning of the word 'really'. I think I have shown below that an absolute positioning solution can easily (for some definition of 'easy') be generalized to any number of data items using any data length 'type'.

But not all things that are easy are wise, and I continue to agree with you and ig that a two-step approach is almost certainly best.

  • Comment on Re^4: how to unpack a C struct with length array preceding data array

Replies are listed 'Best First'.
Re^5: how to unpack a C struct with length array preceding data array
by BrowserUk (Patriarch) on Jun 06, 2013 at 02:01 UTC

    This is what I mean by "not really extensible":

    #! perl -slw use strict; use Benchmark qw[ cmpthese ]; our $I //= -1; our $N //= 4; my @ls = map int( 2+rand 10 ), 1 .. $N; our $str = pack 'S*', @ls; $str .= 'x' x ($_-1) . ' ' for @ls; cmpthese $I, { a => q[ # line 1 "a" my $templ = "S$N" . join( ' ', map{ "\@0 x[S$_] S \@0" . "S$_ x[S${ \( $N-$_ )}]" . '/x' x $_ . '/a' } 0 .. $N-1 ); my( @d ) = unpack $templ, $str; shift @d for 1 .. $N; $I == 1 and print 'a ', join '|', @d; ], b => q[ # line 1 "b" my @l = unpack "S$N", $str; my $templ = "x[S$N]" . join( ' a', '', @l ); my @d = unpack $templ, $str; $I == 1 and print 'b ', join '|', @d; ], }; __END__ C:\test>junk -I=-1 -N=1 Rate a b a 128551/s -- -59% b 312873/s 143% -- C:\test>junk -I=-1 -N=10 Rate a b a 19086/s -- -67% b 57153/s 199% -- C:\test>junk -I=-1 -N=100 Rate a b a 894/s -- -89% b 7979/s 793% --

    You can clean that up by not returning the counts -- which are redundant -- but it is still doing a shit load of extra work in order to avoid two calls to unpack.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.