perl - 对哈希++的澄清

标签 perl operators

我正在阅读 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/

相关文章:

c++ - Perl Win32::API 和指针

perl - 如何从Perl处理程序更改Apache ErrorDocument?

python - 倒序枚举

c# - 在三元/条件运算符中转换时出现奇怪的编译器错误

C 按位逻辑运算难题

regex - 为什么再添加一种替代方法会使我的正则表达式慢600倍?

c++ - 为什么 C++ 需要作用域解析运算符?

带有转换的 Javascript 赋值运算符

python - 使用短路运算符编辑字典

perl - 在 Perl 中递归目录时使用 ARGV