how to access values of a hash which are again a key, value pairs in perl

71 Views Asked by At

I have a hash like below, I need to access it and put that info in an xml. I couldn't access properly. I am facing difficulty in understanding and using hash datatype. Hash that needs to be referred :

$VAR1 = {
          'state1' => {
                        'code' => '328',
                        'num' => '179237'
                      },
          'state2' => {
                        'code' => '987',
                        'num' => '0.8736'
                      },
          'state3' => {
                        'code' => '326',
                        'num' => '582048'
                      }
        };

The xml format I need it to be written is

<Root>

 <Info>
  <statename>state1</statename>
  <code>328<code>
  <num>179237<num>
  </Info>

 <Info>
  <statename>state2</statename>
  <code>987<code>
  <num>0.8736<num>
 </Info>

<Info>
  <statename>state3</statename>
  <code>326<code>
  <num>582048<num>
 </Info>
 
</Root>

I need to use XML::LibXML lib, Apologies for not posting the attempted codes from my end. Since I need it immediately and I am slow at accessing hashes, I am unable to provide any proper working code. Please help. :)

$size = keys %my_hash; 
for(my $i=0; $<=$size;$i++){
 my $tags = $doc->createElement('Info');
 my %tags = 
   statename => 
   code =>
   num => 
}

for my $state_name (sort keys %my_hash){
 my $state_tag = $doc->createElement ($statename);
 my $codetag->appendTextNode($code);
 $num = ->appendChild($statetag) 
}

Please also point to any documentation to learn from beginning to access hashes and use in xmls.

1

There are 1 best solutions below

0
choroba On BEST ANSWER
#! /usr/bin/perl
use warnings;
use strict;

use XML::LibXML;

my %hash = ('state1' => {
                'code' => '328',
                'num' => '179237'
            },
            'state2' => {
                'code' => '987',
                'num' => '0.8736'
            },
            'state3' => {
                'code' => '326',
                'num' => '582048'
            });

my $dom = 'XML::LibXML::Document'->new('1.0', 'UTF-8');
$dom->setDocumentElement(my $root = $dom->createElement('root'));

for my $state (sort keys %hash) {
    my $info = $root->addNewChild("", 'Info');
    $info->addNewChild("", 'statename')->appendText($state);
    for my $key (qw( code num )) {
        $info->addNewChild("", $key)->appendText($hash{$state}{$key});
    }
    $info->appendText("\n");
}
print $dom;