2

很多关于迭代哈希数组的线程,我每天都会这样做。但是现在我想在 AoH 和 AoH 中迭代。我对数组“章节”感兴趣,因为我想为该内部数组的每个数组元素添加一个哈希:

$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'
    },

从理论上讲,这是我想做的事情。

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
4

4 回答 4

6
use warnings;
use strict;

foreach my $criterion (@$criteria) {
  foreach my $chapter (@{$criterion->{chapters}}) {
    print $chapter->{title}, "\n";
  }
}
于 2012-09-11T13:28:30.393 回答
2

像这样迭代数据结构通常比获取所有级别的索引(就像您的代码所做的那样)更容易。这使您可以自己处理每个级别:

for my $criterion (@$criteria) {
    print "$criterion->{title}\n";
    for my $chapter (@{ $criterion->{chapters} }) {
        print "\t$chapter->{title}\n";
    }
}

作为旁注,tot_chaps如果这不是只读数据结构,则密钥是危险的。它很容易与$criterion->{chapters}已经存储在数组中的信息不同步并复制:

my $total_chapters = @{ $criterion->{chapters} };
于 2012-09-11T13:36:34.830 回答
2

我同意 perreal,但要更狭隘地回答你的问题——你的代码应该没问题,除了使用$#$arrayref符号 when$arrayref不再是变量,你使用大括号{},以便 Perl 可以判断引用的范围:

   for my $j ( 0 .. $#{$criteria->[$i]{'chapters'}}) {

(即使$arrayref 一个变量,您也可以使用大括号来明确表示:

for my $i ( 0 .. $#{$criteria} ) {

. 这同样适用于其他解除引用的方式:@$arrayrefor @{$arrayref}%$hashrefor %{$hashref},等等。)

于 2012-09-11T13:30:06.243 回答
0

如果你想添加一些东西,那就去做吧。我不确定我是否了解您要在哪里添加确切的内容。如果您希望每个章节都有另一个键/值对,请这样做:

for my $i ( 0 .. $#$criteria ) {
  for my $j ( 0 .. $#{$criteria->[$i]{'chapters'}}) {
    $criteria->[$i]{'chapters'}->[$j]->{'Teachers Role'} = 'Stuff';
  }
}

此外,代码中还有一个小错误:使用$#{$criteria->[$i]{'chapters'}}而不是$#$criteria->[$i]{'chapters'}因为该$#部分仅在第一个之前有效->,因此它尝试访问->[$i]{'chapters'}out of $#$criteriawhich 是一个数字的值并且不起作用。

于 2012-09-11T13:33:46.037 回答