如何有效地创建连续数字的 Perl 哈希?
我需要创建这样的东西:
my $valueref = {
1 => 1,
2 => 2,
3 => 3,
4 => 4
};
根据某些条件,它可能最多为 40、50 或 60。在每种情况下,它都是连续的整数,如示例中所示。一旦创建,它就永远不会改变,只是传递给预先存在的子例程。由于键和值都是连续的,因此我还可以使用 for
循环创建哈希。我很好奇创建哈希的最快和/或最有效的方法是什么?或者是否还有其他方法可以完成?
I need to create something like this:
my $valueref = {
1 => 1,
2 => 2,
3 => 3,
4 => 4
};
Based on certain conditions, it might be up to 40, or 50 or 60. In each case it would be consecutive integers, as show in the example. Once created, it would never be changed, simply passed to a preexisting subroutine. Since both the keys and the values will be consecutive, I could also create the hash using a for
loop. I was curious what would be the fastest and/or most efficient way to create the hash? Or if there was yet another way it could be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 map 就足够了:
尽管有人可能会注意到这实际上是一个数组...
所以
$valueref->{$n}
实际上是$array[$n]
。我不知道在这种情况下使用哈希是否有任何好处。Using map would suffice:
Though one might note here that this is actually an array...
So
$valueref->{$n}
is actually$array[$n]
. I don't know if there is any benefit to using a hash in this case.我可能会使用
map
来实现此目的:请记住,散列中不能保证顺序。
I'd probably use
map
for this:Remember that order is not guaranteed in a hash.
听起来像是
state
关键字(或闭包):这使得人们能够初始化数据结构,然后不必担心稍后将其作为参数传递。
Sounds like a good candidate for the
state
keyword (or a closure):This enables one to initialize the data structure and then not have to worry about passing it as an argument later on.
哈希片?像这样的事情:
Hash slice? Something like this: