2013-03-08 64 views
1

在以下代碼中,當打印數組的內容時,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'} 
     }; 
+0

順便說一句,'自卸車(@array)'應該是'自卸車(\ @陣列)'。將數組或哈希傳遞給'Dumper'是沒有意義的。 – ikegami 2013-03-08 17:42:29

回答

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); 
4

您存儲所有的散列引用到相同數組引用。這意味着如果您修改@subarray,所有引用它的哈希似乎都會一致地改變。

而是使獨立的淺拷貝作爲

@subarray = ('value2'); 
my $hashref2 = { 
    key1 => 'value2_1', 
    key2 => 'value2_2', 
    key3 => [ @subarray ], 
}; 
push (@array, $hashref2);