How do I reference a Perl hash in an array in a hash?

By : TallGuy
Source: Stackoverflow.com
Question!

This is the code snippet I am working with:

my %photo_details = (
 'black_cat' => (
  ('size' => '1600x1200', 'position' => -25),
  ('size' => '1280x1024', 'position' =>  25),
  ('size' =>   '800x600', 'position' =>   0),
 ),
 'race_car' => (
  ('size' => '1600x1200', 'position' =>  10),
  ('size' =>   '800x600', 'position' =>   5),
 ),
);

my $photo = 'black_cat';

foreach my $photo_detail ($photo_details{$photo})
{
 my $size     = $photo_detail{'size'};
 my $position = $photo_detail{'position'};

 print ("size = $size, position = $position\n");
}

What I am expecting to get is:

size = 1600x1200, position = -25

size = 1280x1024, position = 25

size = 800x600, position = 0

What I do get is:

Use of uninitialized value $size in concatenation (.) or string at C:\Test.pl line 23.

Use of uninitialized value $position in concatenation (.) or string at C:\Test.pl line 23.

size = , position =

The foreach statement is clearly wrong as not only are there no values for $size and $position, it has only gone through the loop once instead of three times. I have tried all sorts of variants of variable prefixes and found none that work.

What am I doing wrong?

By : TallGuy


Answers

There's really only one thing you have to worry about, and that's the top level of the data structure. After that, you just use the right indexing syntax for each level:

If you have a regular hash, you access the key that you want then line up the additional indices for each level after it:

 %regular_hash = ...;
 $regular_hash{$key}[$index]{$key2};

If you have a reference, you do almost the same thing, but you have to start off with the initial dereference with an arrow, -



This video can help you solving your question :)
By: admin