Here's how I might have coded this. The trick here is to remember that when you build deeply nested data structures, each element is a reference to an anonymous hash or array, and you can keep multiple references to the same anonymous data structure (perlreftut, perldsc, perlref). So, I additionally keep references to each node in the temporary structure %nodes so I can easily access them by ID, no matter where they are in the tree. I do make the assumption that the data in the XML is structured correctly: that IDs are unique, each parent_id references an existing ID, that there are no duplicate IDs, that there are no stray nodes, no cycles, and so on.
use warnings; use strict; use XML::LibXML; my $dom = XML::LibXML->load_xml({ location => '11117492.xml' }); # Build the tree my (%nodes,%tree); for my $part ($dom->findnodes('/products/product')) { for my $categories ($part->findnodes('./categories/category')) { my $cat_name = $categories->findvalue("name"); my $cat_id = $categories->findvalue("category_id"); my $cat_parent_id = $categories->findvalue("parent_id"); $nodes{$cat_id}{id} = $cat_id; $nodes{$cat_id}{name} = $cat_name; if ( length $cat_parent_id ) { push @{$nodes{$cat_parent_id}{children}}, $nodes{$cat_id}; } else { $tree{$cat_id} = $nodes{$cat_id} } # root node } } use Data::Dump; dd \%tree; # Debug # Walk the tree to find leaves my @queue = values %tree; while ( @queue ) { my $elem = shift @queue; if ( $elem->{children} ) { push @queue, @{$elem->{children}}; } else { print $elem->{name}," (",$elem->{id},")\n"; } }
Output:
{ 443026 => { children => [ { children => [{ id => 445720, name => "Carrot" }], id => 443120, name => "Vegetables", }, ], id => 443026, name => "Food", }, } Carrot (445720)
Update: Expanded explanation slightly.
In reply to Re: Hash or Array - Logic Help
by haukex
in thread Hash or Array - Logic Help
by audioboxer
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |