2016-04-12 62 views
0

我試圖製作一個嵌套數組的副本,並且似乎我繼續對我的嘗試進行參考。如何在數組結構數組中創建一個嵌套數組的副本

更具體地說,我想要一個數組數組,其中每個子數組都建立在前一個數組上。這裏是我的嘗試:

#!/usr/bin/perl -w 
use strict; 
use warnings; 

my @aoa=[(1)]; 
my $i = 2; 
foreach (@aoa){ 
    my $temp = $_;#copy current array into $temp 
    push $temp, $i++; 
    push @aoa, $temp; 
    last if $_->[-1] == 5; 
} 
#print contents of @aoa 
foreach my $row (@aoa){ 
    foreach my $ele (@$row){ 
    print "$ele "; 
    } 
    print "\n"; 
} 

我的輸出是:

1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 

我想/希望它是:

1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 

我假設我的問題在於我怎麼了分配$ temp,請告訴我是否不是這種情況。任何幫助表示讚賞。

+0

http://stackoverflow.com/questions/388187/whats-the-best-way-to-make-a-deep-copy-of -a-data-structure-in-perl –

+0

一般來說,你可以使用Storable的'dclone'。在這種情況下,zdim的解決方案更合適(因爲你只需要一個簡單的淺拷貝)。 – ikegami

回答

4

my創建一個新陣列,複製要構建的數組的內容,然後添加到它。

保持它儘可能靠近你的代碼

foreach (@aoa) { 
    last if $_->[-1] == 5; 
    my @temp = @$_;   #copy current array into @temp 
    push @temp, $i++; 
    push @aoa, \@temp; 
} 
+0

或者如果你想使用匿名數組,'push @aoa,[@ $ _,$ i ++];' – ikegami

+0

@ikegami非常感謝您的編輯和評論,這會更好。 – zdim