markdibley has asked for the wisdom of the Perl Monks concerning the following question:
Today I needed to turn values in a csv into a chunk of XML (required for an XLST transformation). Because the data in the XML is nested severa layers deep, the csv header describes the location in the XML like a file directory
#id layer/first layer/second id1 value1 value2 id2 value3 value4
The only way I could work out how to build a branch and attach a leaf in a hash was the following. From there I can use XML::Simple to generate the XML. If there was an easier way I would love to know it
output was#!/usr/bin/perl -w use strict; use Data::Dumper; my $list1 = "this/is/a/twig"; my $list2 = "this/is/a/branch"; my $list3 = "this/is/another/branch"; my $hash = {}; my $hashroot = $hash; my @hashtags1 = split(/\//, $list1); my @hashtags2 = split(/\//, $list2); my @hashtags3 = split(/\//, $list3); attach_leaf($hash,\@hashtags1, "leaf1"); attach_leaf($hash,\@hashtags2, "leaf2"); attach_leaf($hash,\@hashtags3, "leaf3"); print Dumper($hashroot); sub attach_leaf{ my ($tree, $branch, $leaf) = @_; # Work along the branch for(my $i = 0; $i < scalar(@$branch); $i++) { # build branch if($i != (scalar(@$branch) - 1)){ # build new branch if it doesn't exist already $tree->{$$branch[$i]} = {} if(! exists $tree->{$$branch[$i +]}); $tree = $tree->{$$branch[$i]}; } # attach leaf else{ $tree->{$$branch[$i]} = $leaf; return $hash; } } }
$VAR1 = { 'this' => { 'is' => { 'a' => { 'branch' => 'leaf2', 'twig' => 'leaf1' }, 'another' => { 'branch' => 'leaf3' } } } };
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Building a tree 1 leaf at a time
by choroba (Cardinal) on Jan 12, 2012 at 23:54 UTC | |
|
Re: Building a tree 1 leaf at a time
by delirium (Chaplain) on Jan 12, 2012 at 20:21 UTC | |
by markdibley (Sexton) on Jan 13, 2012 at 12:13 UTC | |
|
Re: Building a tree 1 leaf at a time
by locked_user sundialsvc4 (Abbot) on Jan 13, 2012 at 14:00 UTC |