在下面的代码中,当打印数组的内容时,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'}
};