“不是哈希引用”创建多维散列(其键能够存储多个值)时,perl 中出现错误
我正在尝试创建一个多维哈希,其键作为数组,以便相同的键可以存储多个值,并且不会被覆盖。
下面是代码片段:
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 行的哈希引用”。任何人都可以帮助解决该错误吗?
谢谢
I am trying to create a multidimensional hash with its keys as an array so that the same keys can store multiple values, and is not overridden.
Below is the code snippet:
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
}
The structure I want is as follows:
{
'15.4' => {
'dev' => [
'ques',
'ques2'
]
'dev2' => [
'ques1',
'ques2'
]
},
'15.2' => {
'dev3' => [
'ques2'
]
}
};
But, I am getting an error "Not a HASH reference at file1.pl line". Can anyone please help in resolving the error?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当你这样做时,你创建了一个数组引用:
然后当你这样做时,你尝试将它用作哈希引用:
很难说出你想要的结构是什么样子,所以我不能真正帮助你提供建议。也许如果你解释一下你想要实现的目标,我可以提供帮助。
随着新结构的更新,这是一种简单的方法来实现
输出(数据结构):
但是,以下批评仍然存在。您没有透露有关数据收集的信息,并且使用数组中的
splice
解决方案并不是很好。您应该返回上一步,谈谈您的数据收集。不过,这并不是创建哈希的好方法。如果您只是想在开始时将值列表分配给数组,请立即将其分配给散列,并且不要将这种奇怪的转换转换为另一个结构。或者,如果您像我怀疑的那样,再次读取文件,请立即创建哈希结构。如果您提供更多详细信息,我可以提供更好的建议。
You create an array reference when you do this:
Then you try to use it as a hash ref when you do this:
Its hard to tell what you want the structure to look like, so I can't really help you with recommendations. Perhaps if you explained what you are trying to achieve, I could help.
With the new structure update, this is a simple way to do it
Output (the data structure):
The below criticism remains, however. There is something you're not telling about your data collection, and this solution with
splice
from an array is not very good. You should go back one step and talk about your data collection.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.