在下面的代码中,当打印数组的内容时,hashref2的key3没有所需的值(我想要实现的是hashref1在key3中有一个数组,其中value1和hashref2在key3中有一个数组,其值为value2)
在代码流程中,我需要首先填充hashrefs,然后将数据推送到子数组。
如果使用对子阵列的引用是正确的方法,请指点一下吗?
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my @array;
my @subarray;
# Puash to array
my $hashref1 = {
key1 => 'value1_1',
key2 => 'value1_2',
key3 => \@subarray
};
push (@array, $hashref1);
# push some data in subarray
push (@subarray, 'value1');
# clear subarray
splice(@subarray);
# Puash to array
my $hashref2 = {
key1 => 'value2_1',
key2 => 'value2_2',
key3 => \@subarray
};
push (@array, $hashref2);
# push some data in subarray
push (@subarray, 'value2');
print "hashref1:\n".Dumper($hashref1);
print "hashref2:\n".Dumper($hashref2);
print "array:\n".Dumper(@array);
出:
hashref1:
$VAR1 = {
'key2' => 'value1_2',
'key1' => 'value1_1',
'key3' => [
'value2'
]
};
hashref2:
$VAR1 = {
'key2' => 'value2_2',
'key1' => 'value2_1',
'key3' => [
'value2'
]
};
array:
$VAR1 = {
'key2' => 'value1_2',
'key1' => 'value1_1',
'key3' => [
'value2'
]
};
$VAR2 = {
'key2' => 'value2_2',
'key1' => 'value2_1',
'key3' => $VAR1->{'key3'}
};
答案 0 :(得分:4)
您正在所有哈希引用中存储对相同数组的引用。这意味着如果您修改@subarray
,则所有引用它的哈希值似乎都会一致更改。
而是在
中制作单独的浅拷贝@subarray = ('value2');
my $hashref2 = {
key1 => 'value2_1',
key2 => 'value2_2',
key3 => [ @subarray ],
};
push (@array, $hashref2);
答案 1 :(得分:2)
我想你还没有完全理解引用是如何工作的。您基本上推送了对同一个数组的引用,因此难怪您拥有与此数组完全相同的内容。
您需要做的是创建一个新的数组引用。这是正确的代码:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my @array;
my $subarray = [];
# Puash to array
my $hashref1 = {
key1 => 'value1_1',
key2 => 'value1_2',
key3 => $subarray
};
push (@array, $hashref1);
# push some data in subarray
push ( @$subarray, 'value1' );
# create a new subarray
$subarray = [];
# Puash to array
my $hashref2 = {
key1 => 'value2_1',
key2 => 'value2_2',
key3 => $subarray
};
push (@array, $hashref2);
# push some data in subarray
push ( @$subarray, 'value2' );
print "hashref1:\n".Dumper($hashref1);
print "hashref2:\n".Dumper($hashref2);
print "array:\n".Dumper(@array);