Reputation: 12858
I am using XML::Simple to load some XML into a data structure which basically contains file/directory information. The problem I am having is iterating through the resulting data structure. I can get to the data I need by using the following:
$lsResults->{file}
If I dump that structure using Dumper, what I see is something like:
$VAR1 = [
{
'owner' => 'reps_hd',
'replication' => '3',
'blocksize' => '134217728',
'permission' => '-rw-r-----',
'path' => '/projects/mdataeng/feeds/customer_care/mail_q_grid_data_20110816.dat',
'modified' => '2011-08-18T21:41:11+0000',
'size' => '625182',
'group' => 'mdataeng',
'accesstime' => '2011-08-18T21:41:11+0000'
},
{
'owner' => 'reps_hd',
'replication' => '3',
'blocksize' => '134217728',
'permission' => '-rw-r--r--',
'path' => '/projects/mdataeng/feeds/customer_care/mail_q_grid_data_20110817.dat',
'modified' => '2011-08-19T23:29:06+0000',
'size' => '600199',
'group' => 'mdataeng',
'accesstime' => '2011-08-19T23:29:06+0000'
},
....
Isn't this basically an array of hash references? I know I can reference the data in the first element by doing:
print Dumper($lsResults->{file}[0]);
$VAR1 = {
'owner' => 'reps_hd',
'replication' => '3',
'blocksize' => '134217728',
'permission' => '-rw-r-----',
'path' => '/projects/mdataeng/feeds/customer_care/mail_q_grid_data_20110816.dat',
'modified' => '2011-08-18T21:41:11+0000',
'size' => '625182',
'group' => 'mdataeng',
'accesstime' => '2011-08-18T21:41:11+0000'
};
So, the question is, how do I iterate through all of the results in the $lsResults->{file} structure to get say the "path" key value for each entry? I know I could manually reference this by doing something like:
print $lsResults->{file}[0]->{path};
print $lsResults->{file}[1]->{path};
print $lsResults->{file}[2]->{path};
print $lsResults->{file}[3]->{path};
But I can't seem to figure out how to iterate through
$lsResults->{file}
What exactly am I doing wrong here?
Upvotes: 0
Views: 3200
Reputation: 14949
Try this:
for my $file ( @{$lsResults->{file}} ) {
print $file->{path};
}
The variable $lsResults->{file}
is actually an array reference, not an array, so you have to de-reference it to iterate over it with the for loop.
Upvotes: 6
Reputation: 46193
You can also use map
to get a list transformation:
use strict;
use warnings;
my @allPaths = map {$_->{path}} @{$lsResults->{file}}
print "$_\n" foreach @allPaths;
Upvotes: 1