[英]Accessing array of hashes in Perl
{}
instead of ()
because if I don't it gave me error.{}
而不是()
因为如果我不这样做,它会给我错误。 How does it see when I use {}? @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";
}
}
Output:输出:
=>21
0:16 16
1:18 18
2:20 20
=>21
0:16 16
1:18 18
2:20 20
2) When I want push a hash to an array I use
{}
instead of()
because if I don't it gave me error.2) 当我想将散列推送到数组时,我使用
{}
而不是()
因为如果我不这样做,它会给我错误。 How does it see when I use{}
?当我使用
{}
时它怎么看?
I can answer this Question 2.我可以回答这个问题 2。
When you use ()
perl sees as list of elements.当您使用
()
perl 将其视为元素列表。 When you use {}
perl sees it as reference to a hash.当您使用
{}
perl 会将其视为对哈希的引用。
So When you do this: push @Arr, (x=>2, y=>5);
所以当你这样做时:
push @Arr, (x=>2, y=>5);
four elements will be pushed to @Arr
: x
, 2
, y
, 5
.四个元素将被推送到
@Arr
: x
, 2
, y
, 5
。 Which is not your intention.这不是你的意图。
But When you do this: push @Arr , {x => 2, y => 5};
但是当你这样做时:
push @Arr , {x => 2, y => 5};
a single reference to an anonymous hash containing x
and y
as the keys, and 2
and 5
as the respective values will be pushed to @Arr
.对包含
x
和y
作为键以及2
和5
作为各自值的匿名哈希的单个引用将被推送到@Arr
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.