shawshankred has asked for the wisdom of the Perl Monks concerning the following question:

Here is the XML Data dumped using the Data Dumper.
$VAR1 = { 'Dev' : { 'NM' : { 'nmsAc' : 'Unknown', 'nmsA' : '0.0.0.0:0' }, 'eve' : { 'alert' : '1', 'debug' : '1' }, 'Com' : { 'cost' : '1', 'stre' : 'nco', }, 'VeCog' : { 'Operations' : { 'A' : { 'Value' : '1', 'Desc' : 'Minmess' }, 'B' : { 'Value' : '10', 'Desc' : 'Minmess' }, 'C' : { 'Value' : '100', 'Desc' : 'Minmess' }, 'D' : { 'Value' : '1000', 'Desc' : 'Minmess' }, } 'disc' : { 'con' : '0.0.0.0:0', 'int' : 'None' } } } };
Here is my Perl Code
use XML::Simple; use Data::Dumper; $xml = new XML::Simple; $data = $xml->XMLin("/home/nager.xml"); print "$data->{Dev}->{VeCog}->{Operations}->{C}->{Value}\n";
I can print the value of element C with the print statement but I cant get the names of the elements A, B, C and D under the Element Operations. I want to be able to print the Key value pairs like
A:1 B:10 C:100 D:1000
How do I do that.

Replies are listed 'Best First'.
Re: How to access the HAsh Reference Elements and Value from XML::Simple out put
by AnomalousMonk (Archbishop) on Sep 16, 2010 at 22:42 UTC

    shawshankred: From your example, you seem to want the keys printed in alpha order. As a convenience, this approach uses a temporary hash reference for the particular hash sub-element you wish to print; of course, it also would be possible (but, IMO, less readable/maintainable) to always access needed elements from the top of the hash down. (The structure of the example HoH I used is less complex than that in the OP, but you get the idea.)

    >perl -wMstrict -le "my %VeCog = ( Operations => { A => { Value => '1', Desc => 'Minmess', }, B => { Value => '10', }, C => { Value => '100', }, D => { Value => '1000', }, }, ); my $tmp_hashref = $VeCog{Operations}; for my $key (sort keys %$tmp_hashref) { print qq{$key:$tmp_hashref->{$key}->{Value}}; } " A:1 B:10 C:100 D:1000

    Update: Also, take a look at the HASHES OF HASHES section ( Access and Printing of a HASH OF HASHES subsection) of the Data Structures Cookbook, perldsc.

      Thanks a lot AnamolousMonk. This works too.
Re: How to access the HAsh Reference Elements and Value from XML::Simple out put
by JavaFan (Canon) on Sep 16, 2010 at 20:58 UTC
    Untested:
    while (my ($key, $value) = each %{$data->{Dev}->{VeCog}->{Operations}} +) { print $key, ":", $value->{Value}, "\n"; }
      Thanks a lot vroom. This works.