The following work fine:
$doc->{computer}[1];
I wasted about 2 hours but can't figure out how to access the same thing using "foreach"
$rows = \@($doc->{computer}) seemed like it should have worked but it didnt.
Once the foreach works, I should be able to use something like
# foreach my $key (keys (%{\@doc->{computer}}) )
# {
# print $doc->{computer}->{$key}->{'id_name'};
# print $doc->{computer}->{$key}->{'ip'};
# }
anyway, the following code can be run from a perl directory but you may want to comment out all the code from line 43 down.
===the following is the output===
C:\perl>test2.p l
$VAR1 = {
'ip' => [
'192.168.0.10'
],
'id_name' => [
'linux1'
]
};
next
$VAR1 = {
'ip' => [
'192.168.0.12'
],
'id_name' => [
'linux2'
]
};
try foreach
C:\perl>
==how to use ForEach and how to use key ?
Thanks for looking!
$doc->{computer}[1];
I wasted about 2 hours but can't figure out how to access the same thing using "foreach"
$rows = \@($doc->{computer}) seemed like it should have worked but it didnt.
Once the foreach works, I should be able to use something like
# foreach my $key (keys (%{\@doc->{computer}}) )
# {
# print $doc->{computer}->{$key}->{'id_name'};
# print $doc->{computer}->{$key}->{'ip'};
# }
anyway, the following code can be run from a perl directory but you may want to comment out all the code from line 43 down.
Code:
use strict;
use warnings;
use XML::Simple;
use XML::Parser;
use Data::Dumper;
my (
$row,
$rows,
@thisxml,
$tree,
$doc
);
@thisxml = (
"<computers>\n",
"<computer>\n",
"<id_name>linux1</id_name>\n",
"<ip>192.168.0.10</ip>\n",
"</computer>\n",
"<computer>\n",
"<id_name>linux2</id_name>\n",
"<ip>192.168.0.12</ip>\n",
"</computer>\n",
"</computers>\n"
);
open (OUT, ">file.xml");
print OUT @thisxml;
close (OUT);
$tree = XML::Simple->new(KeepRoot=>0, ForceArray=>1, SuppressEmpty=>'',);
$doc = $tree->XMLin("file.xml");
print Dumper($doc->{computer}[0]);
print "next\n";
print Dumper($doc->{computer}[1]);
print "try foreach\n";
$rows = \@($doc->{computer});
foreach $row($rows) {
print dumper $row;
print "next\n";
}
C:\perl>test2.p l
$VAR1 = {
'ip' => [
'192.168.0.10'
],
'id_name' => [
'linux1'
]
};
next
$VAR1 = {
'ip' => [
'192.168.0.12'
],
'id_name' => [
'linux2'
]
};
try foreach
C:\perl>
==how to use ForEach and how to use key ?
Thanks for looking!
Comment