你是混淆引用哈希和數組。
數組與聲明:
my @array = (1, 2, 3);
散列聲明瞭:
my %hash = (1 => 2, 3 => 4);
這是因爲這兩個散列和數組是簡單的羅列(花式名單,但我離題)。您只需要使用[]
和{}
就是當您想要使用列表中包含的值,或者您想要創建任一列表的引用(更多,下面)。
注意,=>
只是一個特殊的(即脂肪)逗號,即引用了左側,所以雖然他們做同樣的事情,%h = (a, 1)
將打破,%h = ("a", 1)
工作正常,並%h = (a => 1)
也能正常工作,因爲a
被引用。
數組參考被宣佈爲:
my $aref = [1, 2, 3];
......注意,你需要把陣列基準爲標。如果你不這樣做,做這樣的:
my @array = [1, 2, 3];
...參考被推到的@array
的第一要素,這可能不是你想要的。
散列引用聲明如下:
my $href = {a => 1, b => 2};
的唯一時間是[]
的陣列(不是AREF)上使用的是當你使用它來使用的元素:。同樣對於散列,除非它是參考,否則僅使用{}
來獲得密鑰的值:$hash{a}
。
現在,爲了解決您的問題,您可以繼續使用這些變化的參考文獻:
use warnings;
use strict;
use Data::Dumper;
# declare an array ref with a list of hrefs
my $collection = [
{
'name' => 'Flo',
...
},
{
'name' => 'Flo1',
...
}
];
# dereference $collection with the "circumfix" operator, @{}
# ...note that $row will always be an href (see bottom of post)
foreach my $row (@{ $collection }) {
my $build_status = build_config($row);
print Dumper $build_status;
}
sub build_config {
# shift, as we're only accepting a single param...
# the $row href
my $collect_rows = shift;
return $collect_rows;
}
...或者改變它使用非裁判:
my @collection = (
{
'name' => 'Flo',
...
},
{
'name' => 'Flo1',
...
}
);
foreach my $row (@collection) {
my $build_status = build_config($row);
# build_config() accepts a single href ($row)
# and in this case, returns an href as well
print Dumper $build_status;
}
sub build_config {
# we've been passed in a single href ($row)
my $row = shift;
# return an href as a scalar
return $row;
}
我寫的關於您可能感興趣的Perl參考教程guide to Perl references。還有perlreftut。
最後一點......散列在數組內部聲明爲{}
,因爲它們確實是散列引用。使用多維數據時,只有Perl結構的頂層可以包含多個值。下面的其他內容必須是單個標量值。因此,可以有一個哈希數組,但從技術上和字面上來說,它是一個包含標量的數組,它們的值是對另一個結構的指針(引用)。指針/引用是單個值。
我猜你確實擁有'@collection =(...)',而不是'@collection = [...]'。否則,你會得到'$ VAR1 ='ARRAY(0x20a1d68)';'。 – ThisSuitIsBlackNot
哈..它們之間有什麼區別? (...)用於哈希,[...]用於數組。我對嗎?因爲在代碼中聲明像這樣@collection = [...]。 – Raja