我正在阅读 Damian Conway 的“Perl 最佳实践”并发现以下代码片段:
$have_reconsidered{lc($name)}++;
我想弄清楚这里发生了什么散列。我知道
++
在数字上下文中递增 1,但它对散列有什么作用?来自 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.
所以在上面的例子中,是键值
lc($name)
正在初始化为 0
然后增加到 1
来自 ++
?一般来说,我在哪里可以找到有关
++
行为的更多信息, +=
, 等等...?
最佳答案
%have_reconsidered
是你的哈希。 $name
是一个字符串。 lc($name)
返回小写字符串。 $hash{$key}
将从 hash %hash
返回标量值用 key 存储 $key
.所以:
// get scalar value from hash at key lc($name) and post-increment it
$have_reconsidered(lc($name)}++;
因此,您要做的就是在给定索引(即
lc($name)
)处增加哈希中的值测试用例:
#!/bin/env perl
my %hash = ( 'a' => '2' );
my $name = 'A';
print $hash{lc($name)}++; // prints 2 (incremented after statement)
print $hash{lc($name)}; // prints 3
print ++$hash{lc($name)}; // prints 4 (incremented before statement)
关于perl - 对哈希++的澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6495991/