in reply to Need help with filling a complicated data structure
UPDATE: modified to deal with jumps larger than 1 back up the hierarchy.
Very nice puzzle. Here is my proposal: (it does not do the { inlist => [... bits, but they can be inserted where indicated)
use strict; use warnings; use Data::Dumper; my %type = ( '*' => 'u', '#' => 'o' ); sub type { $type{ substr shift, -1 } } my @lines = map { /([*#]*)(\d*)\s+(.*)/; $2?[$1,[$3,{value=>$2}]]:[$1, + $3] } <DATA>; my @lists = ( [] ); my $lasttype = ''; my $lastitem = $lists[-1]; my @stack; for (@lines) { my( $type, $item ) = @$_; if( not $type ) { push @lists, []; $lastitem = $lists[-1]; $lasttype = ''; @stack = (); next; } if( $type eq $lasttype ) { push @$lastitem, $item; next; } if( not $lasttype ) { push @$lastitem, type($type), [ $item ]; $lastitem = $lastitem->[-1]; $lasttype = $type; push @stack, [ $lastitem, $lasttype ]; next; } if( length( $type ) > length( $lasttype ) ) { # modify this block fo +r { inlist => [... push @stack, [ $lastitem, $lasttype ]; $lastitem->[-1] = [ $lastitem->[-1], [ type($type), [$item] ] ]; $lastitem = $lastitem->[-1]->[1]->[1]; $lasttype = $type; next; } for( 1..(length( $lasttype ) - length( $type )) ) { ( $lastitem, $lasttype ) = @{ pop @stack }; } push @$lastitem, $item; } print Dumper \@lists; __DATA__ * list 1 unordered item 1 * list 1 unordered item 2 *# list 1 unordered item 2 ordered item 1 *# list 1 unordered item 2 ordered item 2 *# list 1 unordered item 2 ordered item 3 * list 1 unordered item 3 ** list 1 unordered item unordered item 1 ** list 1 unordered item unordered item 2 ** list 1 unordered item unordered item 3 **# list 1 unordered item unordered item 3 ordered item 1 **# list 1 unordered item unordered item 3 ordered item 2 **# list 1 unordered item unordered item 3 ordered item 3 * list 1 unordered item 4 # list 2 ordered item 1 #3 list 2 ordered item 2 # list 2 ordered item 3 #* list 2 ordered item 3 unordered item 1 #* list 2 ordered item 3 unordered item 2 #* list 2 ordered item 3 unordered item 3 # list 2 ordered item 4
|
|---|