在以下代碼中,當打印數組的內容時,hash3的key3沒有所需的值(我想要實現的是hashref1在key3中有一個數組, 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'}
};
順便說一句,'自卸車(@array)'應該是'自卸車(\ @陣列)'。將數組或哈希傳遞給'Dumper'是沒有意義的。 – ikegami 2013-03-08 17:42:29