Lots of threads about iterating over an array of hashes, which I do daily. However now I want to iterate over an AoH in and AoH. I’m interested in the array “chapters” because I want to add a hash to each array element of that inner array:
$criteria = [
{
'title' => 'Focus on Learning',
'chapters' => [
{
'content_id' => '182',
'criteria_id' => '1',
'title' => 'Focus on Learning',
},
{
'content_id' => '185',
'criteria_id' => '1',
'title' => 'Teachers Role',
},
{
'content_id' => '184',
'criteria_id' => '1',
'title' => 'Parents in Class',
},
{
'content_id' => '183',
'criteria_id' => '1',
'title' => 'Students at Home',
}
],
'tot_chaps' => '4'
},
This, in theory, is want I want to do.
for my $i ( 0 .. $#$criteria ) {
for my $j ( 0 .. $#$criteria->[$i]{'chapters'}) {
print $criteria->[$i]{'chapters'}->[$j]{'title'}."\n";
}
}
print $criteria->[$i]{'chapters'}->[1]{'title'}."\n"; -> Teachers Role
If you want to add something, just do it. I’m not sure I understood where you want to add what exactly. If you want another key/value pair for each of the chapters, do it like this:
Also, there was a little bug in the code: use
$#{$criteria->[$i]{'chapters'}}instead of$#$criteria->[$i]{'chapters'}because the$#part only works until the first->, so it tries to access->[$i]{'chapters'}out of the value of$#$criteriawhich is a number and doesn’t work.