Perl 中的哈希映射
map
是否有等效的哈希值?
my %new_hash = hash_map { new_key($a) => new_val($b) } %hash;
我知道我可以循环遍历这些键。
Is there a hash equivalent for map
?
my %new_hash = hash_map { new_key($a) => new_val($b) } %hash;
I know that I could loop through the keys.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
List::Pairwise 声称要准确实施该语法 - 请参阅
mapp
、grepp
。不过我还没用过。另外,你可以这样做,
我承认如果
%hash
确实是$deeply->{buried}->{hash}
的话看起来会更笨拙。我更喜欢使用$temp = ...;在这种情况下,映射 {...} 键 %$temp
。List::Pairwise claims to implement exactly that syntax -- see
mapp
,grepp
. I haven't used it though.Also, you can do it as
which I admit looks clumsier if
%hash
is really a$deeply->{buried}->{hash}
. I prefer using$temp = ...; map {...} keys %$temp
in such cases.我真的看不出你想在这里做什么。 “
map
的哈希等价物”是什么意思?您可以在哈希上使用map
就可以了。如果你想要钥匙,只需使用keys
;例如“虽然通常
就可以了。
如果你想要两者,那么使用整个哈希。
对于分配,
%new_hash = %old_hash
有什么问题吗?你有深复制问题吗?然后使用 < code>Storable::dclone。
您希望键和值同时在闭包中可用吗?然后与第一个映射进行一堆对:
我需要查看您想要的示例。这样做,但到目前为止我可以看到使用一些大的旧模块而不是基本 Perl 的零原因。
I really can’t see what you are trying to do here. What does “a hash equivalent for
map
” even mean? You can usemap
on a hash just fine. If you want the keys, just usekeys
; for example"although usually
is just fine.
If you want both, then use the whole hash.
For assignment, what’s wrong with
%new_hash = %old_hash
?Do you have deep-copy issues? Then use
Storable::dclone
.Do you want both key and value available in the closure at the same time? Then make a bunch of pairs with the first map:
I need to see an example of what you would want to do with this, but so far I can see zero cause for using some big old module instead of basic Perl.
您可以像这样使用地图:
You can use map like this:
您可以使用我的模块 List::Genmapn > 为此:
mapn
与 map 类似,只是它需要一个附加参数,即遍历列表的元素数量。在块内,@_
数组设置为当前切片。You can use
mapn
from my module List::Gen to do this:mapn
is like map, except it it takes an additional argument, the number of elements to walk the list by. Inside the block, the@_
array is set to the current slice.$ perl -d /dev/null
例如反转键和值:
$ perl -d /dev/null
To e.g. reverse the key and the value:
从 perl 5.20 开始,核心实用程序
List::Util::pairmap
正是这样做的:它不一定是最佳的(因为它涉及将哈希展开到列表并返回),但我相信这是 vanilla perl 中最短的方法。
As of perl 5.20, core utility
List::Util::pairmap
does exactly that:It's not necessarily optimal (as it involves unrolling the hash to a list and back) but I believe this is the shortest way in vanilla perl.