in reply to Re^2: Convert delimited string into nested data structure
in thread Convert delimited string into nested data structure

Perhaps I should show a bit of code...
my @stack = { name => 'root', level => 0, children => [] }; foreach my $input ( @inputs ) { my @pieces = split /\s+\/\s+/, $input; my $level = scalar @pieces; my $new_node = { name => pieces[-1], level => $level }; if ( $level == $stack[-1]{level} ) { pop @stack; } elsif ( $level < $stack[-1]{level} ) { pop @stack while ( $level <= $stack[-1]{level} ); } # else top level must be our parent push @stack[-1]{children}, $new_node; push @stack, $new_node }
I wrote this up a few years ago.

Phil

Replies are listed 'Best First'.
Re^4: Convert delimited string into nested data structure
by Anonymous Monk on Feb 19, 2007 at 19:16 UTC
    Hi. Thanks for the code, but it has an awful lot of syntax errors in it. Here is the corrected version:
    foreach my $input ( @inputs ) { my @pieces = split /\s+\/\s+/, $input; my $level = scalar @pieces; my $new_node = { name => $pieces[-1], level => $level }; if ( $level == $stack[-1]->{level} ) { pop @stack; } elsif ( $level < $stack[-1]->{level} ) { pop @stack while ( $level <= $stack[-1]->{level} ); } # else top level must be our parent push @{ $stack[-1]->{children} }, $new_node; push @stack, $new_node; }
    Anyways ... this works like a charm. Thanks a lot. :)
Re^4: Convert delimited string into nested data structure
by Anonymous Monk on Feb 19, 2007 at 19:19 UTC
    No, I am afraid I spoke too soon. This does not work at all. Your code produces the following:
    $VAR1 = [ { 'level' => 0, 'name' => 'root', 'children' => [ { 'level' => 1, 'name' => 'one', 'children' => [ { 'level' => 2, 'name' => 'bar' }, { 'level' => 2, 'name' => 'baz', 'children' => [ { 'level' => 3, 'name' => 'two' }, { 'level' => 3, 'name' => 'three' }, { 'level' => 3, 'name' => 'four' } ] } ] }, { 'level' => 1, 'name' => 'five' } ] }, $VAR1->[0]{'children'}[1] ];
    'one' does not have any children.

    Sorry, but this won't work for me either. Maybe this is a harder problem than I thought it would be.

      Ok, I'm sorry I posted code in haste. I wasn't ever trying to give you code you could use. I was only trying to explain the goal. See this article, which I mentioned in passing. I know the code in it works, and there is explanation.

      Phil