2013-06-06 180 views
1

我需要將一個數組數組插入到數組中。並且這個整數數組是一個用於哈希鍵的值。哈希應該是這樣的:Perl:將數組數組插入到一個數組中,該數組是一個鍵值

"one" 
[ 
    [ 
    1, 
    2, 
    [ 
    [ 
     3, 
     4 
    ], 
    [ 
     5, 
     6 
    ] 
    ] 
] 
] 

,其中一個是這裏的關鍵和剩餘部分如果在的哈希鍵的值。觀察數組[3,4]和[5,6]的數組是實際數組中的第三個元素。前兩個元素是1和2.

我寫了一個小程序來做同樣的事情。

#!/usr/bin/perl 
use strict; 
use warnings; 
use Data::Dumper; 
$Data::Dumper::Terse = 1; 
$Data::Dumper::Indent = 1; 
$Data::Dumper::Useqq = 1; 
$Data::Dumper::Deparse = 1; 

my %hsh; 
my @a=[1,2]; 
my @b=[[3,4],[5,6]]; 
$hsh{"one"}=\@a; 
push @{$hsh{"one"}},@b; 
print Dumper(%hsh); 

但這打印如下:

"one" 
[ 
    [ 
    1, 
    2 
    ], #here is where i see the problem. 
    [ 
    [ 
     3, 
     4 
    ], 
    [ 
     5, 
     6 
    ] 
    ] 
] 

我可以看到,數組的數組不插入到所述陣列。 有人可以幫助我嗎?

+0

'[...]'創建一個數組引用,而不是一個數組。所以'@ a = [1,2]'創建一個元素的數組。這可能是你的問題的來源,但我不確定:你預期的數據結構的意圖是令人困惑的。 '@ a =(1,2)'會創建一個包含兩個元素的數組。你確定你不想'%hsh =(one => [1,2,[3,4],[5,6]])? – amon

回答

0
use strict; 
use warnings; 
use Data::Dumper; 
$Data::Dumper::Terse = 1; 
$Data::Dumper::Indent = 1; 
$Data::Dumper::Useqq = 1; 
$Data::Dumper::Deparse = 1; 

my %hsh; 
my @a=(1,2); # this should be list not array ref 
my @b=([3,4],[5,6]); # this should be list conatining array ref 
push (@a, \@b); #pushing ref of @b 
push (@{$hsh{'one'}}, \@a); #pushing ref of @a 

print Dumper(%hsh); 

輸出:

"one" 
[ 
    [ 
    1, 
    2, 
    [ 
     [ 
     3, 
     4 
     ], 
     [ 
     5, 
     6 
     ] 
    ] 
    ] 
] 

更新時間:

my %hsh; 
my @a=(1,2); 
my @b=([3,4],[5,6]); 
push (@a, @b); # removed ref of @b 
push (@{$hsh{'one'}}, @a); #removed ref of @a 

print Dumper(\%hsh); 

Output: 
{ 
    "one" => [ 
    1, 
    2, 
    [ 
     3, 
     4 
    ], 
    [ 
     5, 
     6 
    ] 
    ] 
} 
+0

就是這樣。謝謝Nikhil – user1939168

+0

不客氣。 –

+0

你確定這是它嗎?你似乎有一個額外的數組。看到我的答案。 – ikegami

1

首先,注意:只有通標器以Dumper。如果你想轉儲一個數組或散列,傳遞一個引用。

然後就是你期望的問題。你說你希望

[ [ 1, 2, [ [ 3, 4 ], [5, 6] ] ] ] 

但我覺得你真的希望

[ 1, 2, [ [ 3, 4 ], [5, 6] ] ] 

這兩個錯誤有同樣的原因。

[ ... ] 

裝置

do { my @anon = (...); \@anon } 

所以

my @a=[1,2]; 
my @b=[[3,4],[5,6]]; 

被一個不同的分配給@a(一個匿名數組的引用)的一個單一的元素的單一元素@b(基準匿名數組)。

你真正想要

my @a=(1,2); 
my @b=([3,4],[5,6]); 

所以從

my %hsh; 
$hsh{"one"}=\@a; 
push @{$hsh{"one"}},@b; 
print(Dumper(\%hsh)); 

{ 
    "one" => [ 
    1, 
    2, 
    [ 
     3, 
     4 
    ], 
    [ 
     5, 
     6 
    ] 
    ] 
} 
相關問題