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

Well, I am quite scatter-brained at the moment. Under more ideal circumstances, I would "sleep on this problem" and solve it in the morning -- but I have to get this part done ASAP so I can continue with the larger task at hand.

As such I keep tearing down my past efforts -- but just so you know I am working on this instead of just waiting for others to do my work for me ...

sub recurse { my ($ref, $car, @cdr) = @_; if ($prev_car eq $car) { my $hash = { name => $car, children => [] }; push @$ref, $hash; return unless @cdr; $prev_car = $car; recurse($hash->{children}, @cdr); } push @$ref, { name => $car, children => [] }; return unless @cdr; $prev_car = $car; recurse($ref, @cdr); }
Which produces the following output:
$VAR1 = [ { 'name' => 'one', 'children' => [] }, { 'name' => 'foo', 'children' => [] }, { 'name' => 'bar', 'children' => [] }, { 'name' => 'foo', 'children' => [ { 'name' => 'baz', 'children' => [] } ] }, { 'name' => 'foo', 'children' => [] }, { 'name' => 'baz', 'children' => [] }, { 'name' => 'foo', 'children' => [ { 'name' => 'qux', 'children' => [] }, { 'name' => 'two', 'children' => [] } ] }, { 'name' => 'foo', 'children' => [] }, { 'name' => 'qux', 'children' => [] }, { 'name' => 'two', 'children' => [] }, { 'name' => 'foo', 'children' => [] }, { 'name' => 'qux', 'children' => [] }, { 'name' => 'three', 'children' => [] }, { 'name' => 'foo', 'children' => [] }, { 'name' => 'qux', 'children' => [] }, { 'name' => 'four', 'children' => [] }, { 'name' => 'five', 'children' => [] } ];
I forgot to say "Thanks in advance" too. :)

Replies are listed 'Best First'.
Re^3: Convert delimited string into nested data structure
by educated_foo (Vicar) on Feb 19, 2007 at 19:35 UTC
    If your keys are well-behaved, then this will do the trick:
    while (<>) { chomp; s!\s*/\s*!}{!g; eval "\$h\{$_\} = 1;"; }
      A reply falls below the community's threshold of quality. You may see it by logging in.
      A reply falls below the community's threshold of quality. You may see it by logging in.