[英]Perl How do I retrieve an array from a hash of arrays?
我對Perl很新,所以請原諒我,如果這看起來像一個簡單的問題......
無論如何,我有一個數組哈希,我正在嘗試檢索哈希中的一個數組,但我能得到的只是數組的標量大小。
%HoA = a hash of arrays
$key = some key in the hash
foreach $nextItem (@HoA{$key}) {
do a bunch of stuff with $nextItem
}
當我這樣做時,$ nextItem總是只是數組的大小,循環只運行一次。 我試過打印以下內容:
@HoA{$key}
$HoA{$key}
@$HoA{$key}
前兩個給我標量大小,第三個給了我什么......我在這里缺少什么?
更新:我想知道我的問題是否實際上是我將數組添加到哈希中的方式。 這是我正在做的事情:
@HoA{$key} = split(/ /, $list);
這會將數組粘貼在散列中,還是哈希中的數組大小?
更新2:我嘗試了以下代碼塊:
my $key = "TEST";
my %HoA = ();
my @testarray = (1, 2, 3);
@HoA{$key} = @testarray;
print Dumper(%HoA);
這是輸出:
$VAR1 = 'TEST';
$VAR2 = 1;
為什么它只是堅持數組的第一個值?
嘗試以這種方式引用您的數組:
%HoA = a hash of arrays
$key = some key in the hash
foreach $nextItem (@{$HoA{$key}}) {
do a bunch of stuff with $nextItem
}
您在$HoA{$key}
處獲取數組引用並將其$HoA{$key}
數組。
編輯:對於您的更新,我認為如果您這樣做,我會得到您想要的:
@{$HoA{$key}} = split(/ /, $list);
或者你可以做
push(@{$HoA{$key}}, split(/ /, $list);
例如:
my $list = "fred joe brown sam";
my %HoA = ();
my $key = "jacob";
@{$HoA{$key} = split(/ /, $list);
foreach my $item (@{$HoA{$key}})
{
print "Test item: $nextItem\n";
}
You will get:
Test item: fred
Test item: joe
Test item: brown
Test item: sam
編輯:添加use strict;
到你的程序的頂部。 基本上,當您定義了哈希時,您嘗試將HoA用作數組。 您正在不正確地引用哈希的內容。 要做得恰到好處,你真的需要@
和HoA
之間的$
。 Perl是無類型的,如果你不use strict;
話會讓你逃脫謀殺use strict;
。 來自oreilly的參考摘錄可能會清楚一些事情。
my @testarray
是一個數組
my %hash
是一個哈希
$hash{$el1} = \\@array
是一個散列元素,其值為數組的ref
@{$hash{$el1}} = @array
是一個包含數組的哈希元素
散列中的每個條目都是對數組的引用 。 例如:
$my_hash{$key}
是對數組的引用而不是數組。 $my_hash{$key}
僅指向該數組所在的內存區域。 要取消引用它,您將數組符號放在前面:
@{ my_hash{$key} }
當我們開始談論這些元素時,事情變得有點毛茸茸:
${ my_hash{$key} }[0]
是該數組的第一個元素。 你可以想象如果那個數組由其他數組的哈希組成,那么語法就會變得很明顯。 幸運的是,Perl有一個干凈的處理方式:
$my_hash{$key}->[0];
這與上面完全相同,但更容易理解語法。 有時,使用中間變量更容易,因此您可以在沒有所有解除引用的情況下引用內容:
my %hash_of_array_refs;
foreach my $key (sort keys %hash_of_array_refs) {
my @array = @{ $hash_of_array_refs{$key} }; #Dereference
foreach my $element (@array) { #Much easier to read and understand
say "First element is $array[0]";
say "last element is $array[$#array]";
say "This element: $element";
}
}
沒有解除引用你會得到這個:
my %hash_of_array_refs;
foreach my $key (sort keys %hash_of_array_refs) {
foreach my $element (@{ $hash_of_array_refs{$key} } ) { #Much easier to read and understand
say "First element is " . $hash_of_array_refs->[0];
say "last element is " . $hash_of_array_refs->[$#{ $hash_of_array_refs{key} } ]";
say "This element: $element";
}
}
@array
你如何獲得陣列,所以
@{ $array_ref }
與數組引用等效。
$HoA{$key}
是對數組的引用,所以
@{ $HoA{$key} }
是那個數組。
for my $nextItem (@{ $HoA{$key} })
“為什么它只是堅持數組的第一個值?”
您需要在數組前面添加反斜杠,將數組引用放入哈希:
$HoA{$key} = \@testarray;
然后當您從散列中檢索它時,您將取消引用:
@testarray = @{ $HoA{$key} };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.