No. It should be
0123456789 89a bcdefghijklmn
My solution looks like the following (data structure is slightly modified). Also there is a benchmark against Browser_UK's solution:
use warnings; use strict; use Benchmark; my $text = "0123456789abcdefghijklmn"; my $unpack = ""; my $position = 0; my @fields = ( { name => 'name1', start => 0, len=> 10 }, { name => 'name2', start => 8, len=> 3 }, { name => 'name3', start => 11, len=> 14 }, ); for ( @fields ) { $unpack .= $_->{start} < $position ? 'X' . ( $position - $_->{st +art} ) : $_->{start} > $position ? 'x' . ( $_->{start} - $positi +on ) : ''; $unpack .= 'A' . $_->{len}; $position = $_->{start}+$_->{len}; } print "$unpack\n"; print join ("*", unpack ($unpack, $text)), "\n"; timethese ( 1_000_000, { 'unpack' => sub { my @a = unpack ($unpack, $text); }, 'substr' => sub { my @a = map { substr $text, $_->{start}, $_->{len} } @fie +lds; } }, );
Results:
A10X2A3A14 0123456789*89a*bcdefghijklmn Benchmark: timing 1000000 iterations of substr, unpack... substr: 12 wallclock secs (12.80 usr + -0.02 sys = 12.78 CPU) @ 78 +241.14/s (n=1000000) unpack: 9 wallclock secs ( 9.00 usr + 0.00 sys = 9.00 CPU) @ 11 +1098.77/s (n=1000000)
So it looks like the unpack version is faster, as my guts have said. The cost of assembling the unpack string can be considered irrelevant, because in a real world it would happen only once per file.


holli, /regexed monk/

In reply to Re^2: Challenge: Construct an unpack string by holli
in thread Challenge: Construct an unpack string by holli

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.