Hello

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

#!/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; } } }
output was
$VAR1 = { 'this' => { 'is' => { 'a' => { 'branch' => 'leaf2', 'twig' => 'leaf1' }, 'another' => { 'branch' => 'leaf3' } } } };

In reply to Building a tree 1 leaf at a time by markdibley

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.