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

use strict; use warnings; use Data::Dumper qw( Dumper ); my %tree; while (<DATA>) { chomp; my $p = \%tree; foreach (split(qr{\s*/\s*}, $_)) { $p = $p->{$_} ||= {}; } } print Dumper \%tree; __DATA__ one foo / bar foo / baz foo / qux / two foo / qux / three foo / qux / four five

Replies are listed 'Best First'.
Re^3: Convert delimited string into nested data structure
by eric256 (Parson) on Feb 19, 2007 at 19:32 UTC

    A little recursive sub to compile this into the right format:

    use strict; use warnings; use Data::Dumper qw( Dumper ); my %tree; while (<DATA>) { chomp; my $p = \%tree; foreach (split(qr{\s*/\s*}, $_)) { $p = $p->{$_} ||= {}; } } sub re_format { my $data = shift; my $out = []; for my $key (keys %$data) { my $temp = { name => $key}; if (keys %{ $data->{$key} }) { $temp->{children} = re_format($data->{$key}) } push @$out, $temp; } return $out; } print Dumper('First Step' => \%tree, 'Final' => re_format(\%tree)); __DATA__ one foo / bar foo / baz foo / qux / two foo / qux / three foo / qux / four five

    ___________
    Eric Hodges
      Thank you very much Eric.
      No ... I spoke too soon again. The reformatted data is now out of order. The reason I use a List of Hashes is because I have to preserve the same order.

      In order words, %tree really needs to be @tree.

      Can anybody help me? I have spent far too much time trying to solve this problem. :(
Re^3: Convert delimited string into nested data structure
by Anonymous Monk on Feb 19, 2007 at 19:01 UTC
    Are you suggesting that with a few modifications that I can use your code snippet to achieve my goal? Because I don't see how I can push the children onto their parents using your code (which doesn't produce the output I need).

    But thanks anyways -- good ideas in there.

      Are you suggesting that with a few modifications that I can use your code snippet to achieve my goal? Because I don't see how I can push the children onto their parents using your code (which doesn't produce the output I need).

      Yes, this kind of question has been discussed before. You may also be interested in nodes referenced in that thread. Two modules, that were mentioned in the discussion and that could come useful to make "structured text" into a complex data structure are Data::Hierarchy and Data::Diver.