如何迭代这个Perl结构?

时间:2012-08-30 21:55:55

标签: arrays perl printing hash reference

鉴于以下代码,我试图弄清楚如何遍历散列引用数组(或者至少我认为它是一个散列引用数组)。也就是$Policy->rules()

也许有更好的方法来创建一个结构数组,我愿意接受建议。

use Class::Struct;
use Data::Dumper;

struct Policy => {         
    listings    => '@',  # Will treat like rules eventually.     
    rules       => '@',  # an array of rules      
};

struct Rule => {                
    direction   => '$',        
    id          => '$',        
};

$policy = Policy->new();

$rule1 = Rule->new();
$rule1->direction('Any');
$rule1->id(1);

$rule2 = Rule->new();
$rule2->direction('Inbound');
$rule2->id(2);

$rule3 = Rule->new();
$rule3->direction('Outbound');
$rule3->id(3);

push($policy->rules(),$rule1);
push($policy->rules(),$rule2);
push($policy->rules(),$rule3);

$Data::Dumper::Indent = $Data::Dumper::Terse = 1;
print Dumper \$policy;

输出:

\bless( {
    'Policy::listings' => [],
    'Policy::rules' => [
      bless( {
        'Rule::id' => 1,
        'Rule::direction' => 'Any'
      }, 'Rule' ),
      bless( {
        'Rule::id' => 2,
        'Rule::direction' => 'Inbound'
      }, 'Rule' ),
      bless( {
        'Rule::id' => 3,
        'Rule::direction' => 'Outbound'
      }, 'Rule' )
    ]
  }, 'Policy' )

2 个答案:

答案 0 :(得分:1)

visit_policy($policy);

sub visit_policy {
   my ($policy) = @_;

   my $listings = $policy->listings;
   my $rules    = $policy->rules;

   for my $listing (@$listings) {
      visit_listing($listing);
   }

   for my $rule (@$rules) {
      visit_rule($rule);
   }
}

sub visit_listing {
   my ($listing) = @_;
   # ...
}

sub visit_rule {
   my ($rule) = @_;

   my $direction = $rule->direction;
   my $id        = $rule->id;

   # ...
}

答案 1 :(得分:0)

感谢您的帮助。它看起来很接近,但它仍然需要一些微调。见下文。现在,当我运行它并尝试打印规则 - > id时,我得到以下内容:

无法在D:/SLC/Aiken/Policy/POC/OLAP/test.pl第66行调用未完成引用的方法“方向”。

visit_policy($policy);

sub visit_policy {
   my ($policy) = @_;

   my $listings = $policy->listings;
   my $rules    = $policy->rules;

   for my $listing (@$listings) {
      visit_listing($listing);
   }

   for my $rule (@$rules) {
      visit_rule($rules);
   }
}

sub visit_listing {
   my ($listing) = @_;
   # ...
}

sub visit_rule {
   my ($rule) = @_;

   my $direction = $rule->direction;  #<-- Line 66 
   my $id        = $rule->id;

    print $id . "\n";

   # ...
}