[英]Array of references in Perl
我已經閱讀了參考文檔,但無法弄清楚如何取消對數組中的數組引用的引用。 不明白為什么@{$HoA{$cols[0]}}
只打印數組的長度。 任何澄清都非常感謝。
file.txt
:
aa bb
bb cc
該程序:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
# my $filename = "file.txt";
my @newarray;
my %HoA = (
aa => [ "GAT_1", "GAT_2", "GAT_3", "GAT_4" ],
bb => [ "GAT_6", "GAT_1", "GAT_5", "GAT_4", "GAT_2" ],
cc => [ "GAT_6", "GAT_4", "GAT_3", "GAT_1", "GAT_2" ],
);
open (FILE, '<' ,"$filename") or print "$filename does not exist\n";
while (<FILE>) {
my @cols = split;
$cols[0] = $HoA{ $cols[0] };
#$cols[0] = @{$HoA{ $cols[0]} };
$cols[1] = $HoA{ $cols[1] };
#$cols[1] = @{$HoA{ $cols[1] }};
push ( @newarray, join( " ", @cols ));
}
close FILE;
print Dumper(\@newarray);
這是我的預期輸出:
$VAR1 = [
[
[
'GAT_1',
'GAT_2',
'GAT_3',
'GAT_4'
],
[
'GAT_6',
'GAT_1',
'GAT_5',
'GAT_4',
'GAT_2'
],
[
'GAT_6',
'GAT_1',
'GAT_5',
'GAT_4',
'GAT_2'
],
[
'GAT_6',
'GAT_4',
'GAT_3',
'GAT_1',
'GAT_2'
],
]
];
這是我的實際輸出:
$VAR1 = [
'ARRAY(0x7f80110060e8) ARRAY(0x7f801102eb58)',
'ARRAY(0x7f801102eb58) ARRAY(0x7f801102f308)'
];
最大的問題是此行:
push ( @newarray, join( " ", @cols ));
join
本質上是一個字符串操作: @cols
是一個引用數組,這些join
然后會嚴格按照條件進行字符串化,以便它可以使用" "
。
看來您真正想要的可能是:
push ( @newarray, [@cols] );
其中[ ... ]
表示法創建一個新的匿名數組(在本例中為@cols
的值填充)並返回對其的引用。
此外,代替此:
$cols[0] = $HoA{ $cols[0] };
(這會導致@newarray
和%HoA
最終包含對相同基礎數組的引用),您可能 @newarray
:
$cols[0] = [ @{$HoA{ $cols[0] }} ];
(這樣, @newarray
以完全獨立的數組結尾,這些數組@newarray
與%HoA
數據相同的數據開頭)。 這取決於您是否打算在以后修改任何陣列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.