【发布时间】:2021-05-06 00:19:44
【问题描述】:
我有一个数组和哈希定义为:
my @test_array;
my %test_hash = (
line_1 => 1,
line_2 => 2,
line_3 => 3,
);
我想将该哈希添加到数组中,然后修改哈希并将任何新版本推送到数组中
push (@test_array, %test_hash);
$test_hash{line_1} = 2;
push (@test_array, %test_hash);
最后,我需要在传入数组中的每个哈希时调用一个方法,一次一个:
for my $hash (@test_array) {
$self->do_thing(%$hash)
}
但是,当我打印出数组时,似乎两个哈希都存储在一个元素中:
use Data::Dumper;
print Dumper (\@test_array);
### Begin Output ###
$VAR1 = [
'line_1',
1,
'line_3',
3,
'line_2',
2,
'line_1',
2,
'line_3',
3,
'line_2',
2
];
我的方法调用本质上应该如下所示,line_1 => 2 在第二次循环中的散列中:
$self->do_thing(
line_1 => 1,
line_2 => 2,
line_3 => 3,
);
有人能解释一下为什么这一切都被添加到一个数组元素中吗?我希望 Dumper 输出将包含一个用于第一个推送哈希的 $VAR1 和一个用于第二个哈希的 $VAR2 - 但事实并非如此。
谢谢!
【问题讨论】:
-
哈希和数组只能包含标量,不能包含哈希和数组。作为一种“解决方法”,我们将哈希和数组的引用存储在哈希和数组中,因为它们是标量。
标签: arrays perl dereference