关于哈希的澄清++
我正在阅读 Damian Conway 的“Perl 最佳实践”,并发现以下代码片段:
$have_reconsidered{lc($name)}++;
我试图弄清楚哈希值到底发生了什么。我知道 ++
在数字上下文中加一,但它对哈希有什么作用?
来自 perlop 文档:
undef 始终被视为数字, 特别是更改为 0 在递增之前(这样a undef 值的后增量将 返回 0 而不是 undef)。这 自减运算符不是 神奇的。
因此,在上面的示例中,键 lc($name)
的值被初始化为 0
,然后通过 增加到
1
>++?
一般来说,我在哪里可以找到有关 ++
、+=
等行为的更多信息...?
I am reading Damian Conway's "Perl Best Practices" and found the following code snipet:
$have_reconsidered{lc($name)}++;
I am trying to figure out what is going on here with the hash. I know ++
increments by one in a numeric context, but what does it do to a hash?
From perlop documentation:
undef is always treated as numeric,
and in particular is changed to 0
before incrementing (so that a
post-increment of an undef value will
return 0 rather than undef). The
auto-decrement operator is not
magical.
So in the example above, is the value for the key lc($name)
being initialized to 0
and then incremented to 1
by ++
?
In general, where could I find out more about the behaviors of ++
, +=
, etc...?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
%have_reconsidered
是您的哈希值。$name
是一个字符串。lc($name)
返回小写字符串。$hash{$key}
将从使用键$key
存储的哈希%hash
返回标量值。所以:所以,您所做的就是在给定索引(即
lc($name)
)处增加哈希值测试用例:
%have_reconsidered
is your hash.$name
is a string.lc($name)
returns the lowercased string.$hash{$key}
will return the scalar value from hash%hash
stored with key$key
. so:so, all you do is increment the value in a hash at a given index (namely
lc($name)
)test case:
哈希值是标量,因此
$have_reconsidered{lc($name)}++;
会递增标量$have_reconsidered{lc($name)}
。如果该标量之前未定义或不存在,++
会将其设置为 1。此代码的目标可能是删除重复项。
我更喜欢类似但不同的方法,因为它保留了秩序。
Hash values are scalars, so
$have_reconsidered{lc($name)}++;
increments the scalar$have_reconsidered{lc($name)}
. If that scalar was previously undefined or didn't exist,++
will set it to 1.The goal of this code is probably to remove duplicates.
I prefer a similar but different approach because it preserves order.
$have_reconsidered{lc($name)} 是属于键 lc($name) 的散列 %have_reconsidered 的值。该值肯定可以是数字,但即使它是字符串,它仍然可以自动递增(请参见http://perldoc.perl.org/perlop.html#Auto-increment-and-Auto-decrement)。
$have_reconsidered{lc($name)} is the value of the hash %have_reconsidered that belongs to the key lc($name). This value could definitely be numeric, but even if it is a string, it can still be auto-incremented (see http://perldoc.perl.org/perlop.html#Auto-increment-and-Auto-decrement).