Holly
Holly

Reputation: 333

perl accessing multidimensional arrays

I'm using the Perl TMDB module

How would I get the elements in the example from the code below so

my $width = '1000' and my $file_path = "/yDIVWFJqFLIeS8E1R6GG9uwPMS3.jpg"

my @images = $movie->images;

# print " <p>backdrops </p>";
print OUT JSON::to_json(\@images) ; ## Dump.txt below

foreach my $image (@images) {
   #print $movie->cast;
   my $backdrops = $image->{backdrops};
   my $posters = $image->{posters};      
   #print " <p>backdrops" . JSON::to_json(\@backdrops) . "</p>";

     foreach my $backdrop ($image{backdrops}) {
         my $width = $backdrop->{width};
         my $file_path= $backdrop->{file_path};
         print " <p>backdrops </p>";
         print "<div>width : $width <br />$file_path : $file_path </div>";  
     }
}

Sample of Dump.txt

[{
  "posters":
    [{"vote_average":5.89446589446589,"aspect_ratio":0.67,"width":1000,"file_path":"/yDIVWFJqFLIeS8E1R6GG9uwPMS3.jpg","vote_count":11,.....}],
  "id":60304,
  "backdrops":
    [{"vote_average":5.49206349206349,"aspect_ratio":1.78,"width":1920,"file_path":"/4wieJ74tXkZDMiiwJ6yMr7LgSpR.jpg","vote_count":11,.....}]
}]

Upvotes: 0

Views: 134

Answers (1)

Dave Cross
Dave Cross

Reputation: 69224

foreach my $backdrop ($image{backdrops}) {
  ... 
}

There are two problems with this code. You would have found the first by including use strict in your code. That would have pointed out that you are trying to access a hash called %image where no such hash exists. You actually have a hash reference that is stored in a scalar variable called $image. So you need to access the values using the -> syntax, not a direct hash look-up.

 foreach my $backdrop ($image->{backdrops}) {
   ... 
 }

Now we're getting to $image->{backdrops}, but what is in that value? You are treating it like a list or an array. But it's actually an array reference. So you need to de-reference this reference in order to get back to the array. You do this using @{ ...}.

 foreach my $backdrop (@{ $image->{backdrops} }) {
   ... 
 }

That should work.

Upvotes: 5

Related Questions