#!/usr/bin/perl -w use strict; use XML::Simple; my $xml = qq|Of course I will be putting in some dynamic XML when I get this to work, so I need to know how many elements were returned so I can get city, state, and zip information out for each entry. Here are the results of the above code, and obviously the count is 1 because that is how many arrays there are. I am sure it is not overly complicated, I have just tried and tried to no avail.|; my $perl = XMLin($xml); use Data::Dumper; my @table = $perl->{Table}; my @newtable = $table[0]; my $count = @newtable; print Dumper(\@newtable); print "Count is $count\n"; print "State is $newtable[0][3]{STATE}\n";
Provo UT 84601 801 M
Provo UT 84605 801 M
Provo SD 57774 605 C
Provo KY 42267 502 E
$VAR1 = [
[
{
'STATE' => 'UT',
'ZIP' => '84601',
'AREA_CODE' => '801',
'TIME_ZONE' => 'M',
'CITY' => 'Provo'
},
{
'STATE' => 'UT',
'ZIP' => '84605',
'AREA_CODE' => '801',
'TIME_ZONE' => 'M',
'CITY' => 'Provo'
},
{
'STATE' => 'SD',
'ZIP' => '57774',
'AREA_CODE' => '605',
'TIME_ZONE' => 'C',
'CITY' => 'Provo'
},
{
'STATE' => 'KY',
'ZIP' => '42267',
'AREA_CODE' => '502',
'TIME_ZONE' => 'E',
'CITY' => 'Provo'
}
]
];
Count is 1
State is KY
my @table = $perl->{Table};
my @newtable = $table[0];
my $count = @newtable;
But $perl->{Table} returns an array reference, not an array. Instead, do:
my @table = @{ $perl->{Table} };
my $count = @table;
Now $count should be accurate, and @table should hold hash references (I think).
my $perl = XMLin($xml);
Calling XMLin() without specifying any options is often a bug waiting to happen, see [id://218480|this node].
Also, when looking for meaningful variable names, it might help to bear in mind that XMLin will throw away the top-level XML element name by default - why not use that:
my $NewDataSet = XMLin($xml, KeyAttr => [], ForceArray => ['Table']);
Then when you index into the data, the Perl symbols and the XML element names correspond naturally:
my $table = $NewDataSet->{Table};
my $table_count = @$table;
perlmonks.org content © perlmonks.org and grantm, inblosam, japhy
prlmnks.org © 2006 edmund von der burg (eccles & toad)
v 0.03