我正在嘗試創建一個多維哈希,其鍵作為陣列,以便相同的鍵可以存盤多個值,并且不會被覆寫。
下面是代碼片段:
my %hashR;
my @RelDiv = qw(15.4 dev ques 15.4 dev ques2 15.4 dev2 ques1 15.4 dev2 ques2
15.2 dev3 ques2);
while (my $RName = shift @RelDiv) {
my $ProStr = shift @RelDiv;
push @{$hashR{$RName}}, $ProStr;
my $BName = shift @RelDiv ; ## Working file till here (tried printing the values)
push @{$hashR{$RName}{$ProStr}}, $BName; ###### Error on this line
}
我想要的結構如下:
{
'15.4' => {
'dev' => [
'ques',
'ques2'
]
'dev2' => [
'ques1',
'ques2'
]
},
'15.2' => {
'dev3' => [
'ques2'
]
}
};
但是,我收到一個錯誤“不是 file1.pl 行的 HASH 參考”。任何人都可以幫助解決錯誤嗎?
謝謝
uj5u.com熱心網友回復:
執行此操作時創建一個陣列參考:
push @{$hashR{$RName}}, $ProStr;
# means: $hashR{$RName} = [ $ProStr ]
然后在執行此操作時嘗試將其用作哈希參考:
push @{ $hashR{$RName}{$ProStr} }, $BName; ###### Error on this line
# ^^^-- here
很難說出你想要的結構是什么樣的,所以我真的不能幫你推薦。也許如果您解釋了您要達到的目標,我可以提供幫助。
隨著新結構的更新,這是一種簡單的方法
use strict;
use warnings;
use Data::Dumper;
my %hash;
my @RelDiv = qw(15.4 dev ques 15.4 dev ques2 15.4 dev2 ques1 15.4 dev2 ques2 15.2 dev3 ques2);
while (@RelDiv) {
my ($RName, $ProStr, $BName) = splice @RelDiv, 0, 3;
push @{ $hash{$RName}{$ProStr} }, $BName;
}
print Dumper \%hash;
輸出(資料結構):
$VAR1 = {
'15.4' => {
'dev2' => [
'ques1',
'ques2'
],
'dev' => [
'ques',
'ques2'
]
},
'15.2' => {
'dev3' => [
'ques2'
]
}
};
然而,下面的批評仍然存在。有些事情你沒有告訴你的資料收集,這個splice來自陣列的解決方案不是很好。你應該退一步談談你的資料收集。
Its not a very good way to create a hash, though. If you are just going to assign a list of values to an array at the start, instead assign it to the hash right away and don't do this strange conversion into another structure. Or if you are, as I suspect, reading from a file, again, create the hash structure right away. If you give more detail, I can provide better recommendations.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/435092.html
