My solution looks like the following (data structure is slightly modified). Also there is a benchmark against Browser_UK's solution:0123456789 89a bcdefghijklmn
Results: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; } }, );
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.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)
In reply to Re^2: Challenge: Construct an unpack string
by holli
in thread Challenge: Construct an unpack string
by holli
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |