在Perl中访问哈希数组

时间:2016-08-07 21:13:29

标签: arrays perl hash

我在创建数据后访问数组的每个元素中的哈希有问题,但它给出了最后一个元素。我该怎么做才能访问我的数组的所有元素?

@stem = ();
for($i=0;$i<2;++$i){
    push @stem,{u1=>1 , u2 => 2 , u3 => 3};
}
@ants = ();
$count = 0;
for($i=0;$i<scalar(@stem);++$i){
    @allowed = ();
    %hash = ();

    for($j=0;$j<scalar(@stem);++$j){
        push @allowed,{stem=>++$count,hinfo=>++$count};
    }
    %hash = ( allowed=>\@allowed ,solution=>++$count);
    push (@ants,\%hash);

}

for($i=0;$i<scalar(@ants);++$i){
    %test = %{$ants[$i]};
    print "=>",$test{solution},"\n";
    @temp = @{$test{allowed}};
    for($j=0;$j<scalar(@temp);++$j){
        print $j,":",$temp[$j]->{stem}," ",$temp[$j]->{hinfo},"\n";
    }
}

输出:
=&GT; 21个
0:16 16
1:18 18
2:20 20
=&GT; 21个
0:16 16
1:18 18
2:20 20

1 个答案:

答案 0 :(得分:0)

由于只有一个变量@allowed和一个变量%hash,您可以在其中获取相同的值(在循环的最后一次迭代中清除并设置)

在循环中声明它们,每次循环时都会获得对新变量的引用:

for($i=0;$i<scalar(@stem);++$i){
    my @allowed;
    my %hash;

    for($j=0;$j<scalar(@stem);++$j){
        push @allowed,{stem=>++$count,hinfo=>++$count};
    }
    %hash = ( allowed=>\@allowed ,solution=>++$count);
    push (@ants,\%hash);
}