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

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

Replies are listed 'Best First'.
Re^4: Convert delimited string into nested data structure
by Anonymous Monk on Feb 19, 2007 at 20:04 UTC
    Thank you very much Eric.
Re^4: Convert delimited string into nested data structure
by Anonymous Monk on Feb 19, 2007 at 20:25 UTC
    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. :(