in reply to Re: Generation of a Hash of Hashes
in thread Generation of a Hash of Hashes

$result{1}{12}{0}? Because that's what it seems you want to do by looking at "ITEM", "Sub Item 1"... OTOH, "Item X" and "And Another Item" aren't placed after a 0 either...

Trees are a PITA, plain and simple. What you're not seeing in the example is that there's some extra logic being assumed, that makes sense to someone who's dealing with the a variable depth structure, but actually makes it more difficult to parse overall. (when it's a leaf, and not a branch, it's using different syntax -- which is annoying, when you have to add a branch there, and move the leaf)

Of course, I don't know if there's something already in place to deal with the structure. If I were starting from scratch, I'd probably use something like:

#!/usr/bin/perl -- use strict; use warnings; use Data::Dumper; my %result = (); foreach my $line (<DATA>) { chomp $line; my ($index, $value) = split(/ /, $line, 2); my $temp = \%result; foreach my $path (split (//, $index)) { $temp = $temp->{$path} ||= {} } $temp->{0} = $value; } print Dumper \%result; __DATA__ 1 ITEM 11 Sub Item 1 111 Item X 112 Item 1121 Another Item 11212 And Another Item 12 Sub Item 2

Of course, this assumes that 0 is never used as an index, and with this structure is that the individual items need to know their path up the tree to get their whole code. If the indexes are always numbers, the following may be useful:

my %result = (); foreach my $line (<DATA>) { chomp $line; my ($index, $value) = split(/ /, $line, 2); my $temp = \%result; foreach my $path (split (//, $index)) { $temp = $temp->{$path} ||= {} } $temp->{''} = [$index, $value]; }

(and I'm surprised that tilly and I both use the same method for walking trees ... anyone else have another way to do it?)