in reply to split string by character count

I'm assuming the 1:, 2:, etc. aren't actually in @list. You said you wanted to end up with an array; how about this:

#!/usr/bin/perl -w use strict; my $string = "21090412500011 209 070279501 9047 +0 1111"; my @list = ("date", 6, "time", 4, "duration", 4, "calling-num", 15, "dialed-num", 18, "code-used", 4, "cond-code", 1, "ppm", 5, "auth-code", 13,); my @anotherlist; my $ptr = 0; while(1){ push(@anotherlist, shift(@list)); my $length = shift(@list); push(@anotherlist, substr($string, $ptr, $length)); $ptr += $length; last if $ptr >= length($string); } print "@anotherlist\n";

TheEnigma

Replies are listed 'Best First'.
Re^2: split string by character count
by ikegami (Patriarch) on Sep 21, 2004 at 14:49 UTC

    For added utility, convert the array to a hash:

    sub extract_fields { my @anotherlist; my $ptr = 0; while (@list) { push(@anotherlist, shift(@list)); my $length = shift(@list); if ($ptr >= length($string)) { push(@anotherlist, undef); } else { push(@anotherlist, substr($string, $ptr, $length)); } $ptr += $length; } push(@anotherlist, '_leftover', substr($string, $ptr)) if ($ptr < length($string)); return @anotherlist; } %fields = extract_fields(...);