in reply to Challenge: Construct an unpack string
Given the form of the input and that the fields can overlap (assuming that was intentional), using unpack for this is awkward and inefficient.
You have to parse the input spec. from it's absolute pos/length pairs into the relative form (length/backspace) form required by unpack and build the string template. But the unpack has to parse the string template and convert that back into the position/offset pairs to perform the extractions.
Much simpler, (and with having benchmarked, I'll bet quicker), to use substr for this directly:
C:\test>p1 [0] Perl> $str = join'', 'a'..'z',0..9,'A'..'Z';; [0] Perl> @fields = ( [ name1 => { start => 0, len=> 10 } ], [ name2 => { start => 8, len=> 3 } ], [ name3 => { start => 11, len=> 14 } ], );; ## This one line does all the work! [0] Perl> @bits = map{ substr $str, $_->[1]{start}, $_->[1]{len} } @fi +elds;; [0] Perl> print for @bits;; abcdefghij ijk lmnopqrstuvwxy
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Challenge: Construct an unpack string
by atcroft (Abbot) on Sep 26, 2006 at 18:50 UTC | |
by BrowserUk (Patriarch) on Sep 26, 2006 at 19:17 UTC | |
by BrowserUk (Patriarch) on Sep 26, 2006 at 19:22 UTC |