2011-11-07 73 views
9

考慮以下代碼:如何將從函數(如split)返回的數組轉換爲數組引用?

@tmp = split(/\s+/, "apple banana cherry"); 
$aref = \@tmp; 

除了是不雅的,上面的代碼是脆弱的。說我跟着它與這條線:

@tmp = split(/\s+/, "dumpling eclair fudge"); 

現在$$aref[1]是「閃電」,而不是「香蕉」。

如何避免使用temp變量?

概念,我想的有點像

$aref = \@{split(/\s+/, "apple banana cherry")}; 
+4

函數不能返回數組。 'split'返回一個標量列表,就像任何子標籤一樣。 – ikegami

回答

19

如果你想要一個數組,裁判你可以這樣做:

my $aref = [ split(/\s+/, "apple banana cherry") ]; 
3

我想通了:

$aref = [split(/\s+/, "apple banana cherry")]; 
2

雖然我喜歡mu的回答(並且會在這裏首先使用這種方法),但請記住,變量可以相當容易地作用於範圍,即使請使用函數,想象一下:

my $aref = do { 
    my @temp = split(/\s+/, "apple banana cherry"); 
    \@temp; 
}; 
print join("-", @$aref), "\n"; 
# with warnings: Name "main::temp" used only once: possible typo at ... 
# with strict: Global symbol "@temp" requires explicit package name at ... 
print join("-", @temp), "\n"; 

快樂編碼。

相關問題