Perl:哈希中数组中的哈希
我正在尝试构建一个将数组作为一个值的哈希;该数组将包含哈希值。不幸的是,我编码错误,它被解释为伪哈希。请帮忙!
my $xcHash = {};
my $xcLine;
#populate hash header
$xcHash->{XC_HASH_LINES} = ();
#for each line of data
$xcLine = {};
#populate line hash
push(@{$xcHash->{XC_HASH_LINES}}, $xcLine);
foreach $xcLine ($xcHash->{XC_HASH_LINES})
#psuedo-hash error occurs when I try to use $xcLine->{...}
I am trying to build a Hash that has an array as one value; this array will then contain hashes. Unfortunately, I have coded it wrong and it is being interpreted as a psuedo-hash. Please help!
my $xcHash = {};
my $xcLine;
#populate hash header
$xcHash->{XC_HASH_LINES} = ();
#for each line of data
$xcLine = {};
#populate line hash
push(@{$xcHash->{XC_HASH_LINES}}, $xcLine);
foreach $xcLine ($xcHash->{XC_HASH_LINES})
#psuedo-hash error occurs when I try to use $xcLine->{...}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
$xcHash->{XC_HASH_LINES}
是一个 arrayref 而不是一个数组。所以应该是:
foreach
接受一个列表。它可以是包含单个标量的列表 (foreach ($foo)
),但这不是您想要的。应该是:
$xcHash->{XC_HASH_LINES}
is an arrayref and not an array. Soshould be:
foreach
takes a list. It can be a list containing a single scalar (foreach ($foo)
), but that's not what you want here.should be:
应该
参见 http://perlmonks.org/?node=References+quick+reference 易于记住如何取消引用复杂数据结构的规则。
should be
See http://perlmonks.org/?node=References+quick+reference for easy to remember rules for how to dereference complex data structures.
黄金法则 #1
一开始可能看起来像是一场战斗,但他们会灌输良好的 Perl 实践,并帮助识别许多否则可能会被忽视的语法错误。
另外,Perl 有一个巧妙的功能,称为自动生存。这意味着
$xcHash
和$xcLine
不需要预先定义或构造为对数组或哈希的引用。这里面临的问题与标量可以保存数组或散列这一并不罕见的概念有关;事实并非如此。它所包含的内容是一个参考。这意味着
$xcHash->{XC_HASH_LINES}
是一个 arrayref,而不是数组,这就是为什么需要使用@{...}< /code> 符号。
Golden Rule #1
It might seem like a fight at the beginning, but they will instill good Perl practices and help identify many syntactical errors that might otherwise go unnoticed.
Also, Perl has a neat feature called autovivification. It means that
$xcHash
and$xcLine
need not be pre-defined or constructed as references to arrays or hashes.The issue faced here is to do with the not uncommon notion that a scalar can hold an array or hash; it doesn't. What it holds is a reference. This means that the
$xcHash->{XC_HASH_LINES}
is an arrayref, not an array, which is why it needs to be dereferenced as an array using the@{...}
notation.这就是我要做的:
对于每一行数据:
Here's what I would do:
for each line of data: