在 perl 中是否有简单的语法来声明具有一个值的多个键?
有没有一种简单的方法来声明具有多个键的散列,这些键都指向 perl 中的相同值?
这是与我正在寻找的类似的东西(我实际上不知道这是否有效):
my $hash = {
a, b, c => $valA,
d, e, f => $valB
};
这样......
print $hash->{a}; #prints $valA
print $hash->{b}; #prints $valA
print $hash->{c}; #prints $valA
print $hash->{d}; #prints $valB
print $hash->{e}; #prints $valB
print $hash->{f}; #prints $valB
Is there a simple way to declare a hash with multiple keys which all point to the same value in perl?
Here is something similar to what I'm looking for (I don't actually know if this works or not):
my $hash = {
a, b, c => $valA,
d, e, f => $valB
};
such that....
print $hash->{a}; #prints $valA
print $hash->{b}; #prints $valA
print $hash->{c}; #prints $valA
print $hash->{d}; #prints $valB
print $hash->{e}; #prints $valB
print $hash->{f}; #prints $valB
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
你可以这样写:
You can write this:
不,没有简单的语法。 (实际上,
=>
被记录为,
的别名,其唯一的正式效果是即使在严格模式下,它也允许在其左侧出现裸字)。在不定义自己的潜艇的情况下,你可以做的最好的事情可能是这样的
No, there is no simple syntax for this. (Actually,
=>
is documented to be an alias for,
whose only formal effect is that it allows a bareword to the left of it even in strict mode).The best you could do without defining your own subs might be something like
我喜欢在一侧使用哈希片,在另一侧使用列表复制运算符。我使用键数组的标量值来计算要复制的值的数量:
I like to use a hash slice on one side and the list replication operator on the other. I use the scalar value of the keys array to figure out how many values to replicate:
没有内置语法,但您始终可以编写自己的语法:
如果您要经常这样做,您可能需要查看
Hash::Util
的hv_store< /code> 函数,它允许您加载具有完全相同的内存位置的多个密钥。
There is no built in syntax, but you can always write your own:
If you are going to be doing this a lot, you might want to look at
Hash::Util
'shv_store
function, which allows you to load multiple keys with exactly the same memory location.您可以使用哈希切片分配:
You can use hash slice assignment:
也可以使用语句来完成赋值,例如使用
map
。在这里,map 将扩展为两个列表。Assignment can be done with statements too, such as with
map
. Here, map will expand into two lists.是的,正如 Henning Makholm 指出的那样,没有直接的快捷方式,因为
=>
是,
的别名。我能想到的最接近快捷方式的是:Yeah, as Henning Makholm pointed out, there is no direct shortcut, since
=>
is an alias for,
. The closest thing to a shortcut I can think of is: