如何在 Perl 中创建哈希数组并循环遍历它们?
我正在尝试创建一个哈希数组,但在循环该数组时遇到问题。我已经尝试过这段代码,但它不起作用:
for ($i = 0; $i<@pattern; $i++){
while(($k, $v)= each $pattern[$i]){
debug(" $k: $v");
}
}
I'm trying to create an array of hashes, but I'm having trouble looping through the array. I have tried this code, but it does not work:
for ($i = 0; $i<@pattern; $i++){
while(($k, $v)= each $pattern[$i]){
debug(" $k: $v");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,为什么不
使用
strict
和警告
?以下几行应该位于您创建的每个 Perl 程序的顶部,紧接在#!/usr/bin/perl
之后。 总是。我知道你不是,因为我很确定你会从
strict
和warnings
中以及你的许多其他地方得到一些不错的错误消息。代码也是如此,根据您的变量使用来判断。其次,为什么不这样做:
循环遍历
@pattern
中的每个元素,一次将它们分配给$i
一个。然后,在循环中,当您需要特定元素时,只需使用$i
即可。对$i
的更改将反映在@pattern
中,当循环退出时,$i
将超出范围,本质上是在之后清理本身。第三,出于 Larry Wall 的热爱,请使用
my
声明您的变量以本地化它们。这真的没那么难,而且它会让你成为一个更好的人,我保证。第四,也是最后一点,您的数组存储对哈希值的引用,而不是哈希值。如果他们存储哈希值,您的代码将是错误的,因为哈希值以
%
开头,而不是$
。事实上,引用(任何类型)都是标量值,因此以$
开头。所以我们需要取消引用它们来获取哈希值:或者,你的方式:
First, why aren't you
use
ingstrict
andwarnings
? The following lines should be at the top of every Perl program you create, right after#!/usr/bin/perl
. Always.And I know you aren't because I'm pretty sure you'd get some nice error messages out of
strict
andwarnings
from this, and from many other places in your code as well, judging by your variable use.Second, why aren't you doing this:
That loops through every element in
@pattern
, assigning them to$i
one at a time. Then, in your loop, when you want a particular element, just use$i
. Changes to$i
will be reflected in@pattern
, and when the loop exits,$i
will fall out of scope, essentially cleaning up after itself.Third, for the love of Larry Wall, please declare your variables with
my
to localize them. It's really not that hard, and it makes you a better person, I promise.Fourth, and last, your array stores references to hashes, not hashes. If they stored hashes, your code would be wrong because hashes start with
%
, not$
. As it is, references (of any kind) are scalar values, and thus start with$
. So we need to dereference them to get hashes:Or, your way:
试试这个:
您尝试的最大问题是
每个$pattern[$i]
。 each 函数需要一个哈希来工作,但是$pattern[$ i]
返回一个 hashref(即对哈希的引用)。您可以通过取消引用$pattern[$i]
作为哈希来修复代码:另外,请注意每个函数,它可以 让哈希迭代器处于不完整状态。
Try this instead:
The biggest problem with what you were trying was
each $pattern[$i]
. The each function expects a hash to work on, but$pattern[$i]
returns a hashref (i.e. a reference to a hash). You could fix your code by dereferencing$pattern[$i]
as a hash:Also, beware of the each function, it can leave the hash iterator in an incomplete state.
请参阅 perl 数据结构手册的文档:
perldoc perldsc
See the documentation for the perl data structures cookbook:
perldoc perldsc