3

在尝试减少一些默认哈希码时,我发现您可以添加到 none 以产生 none 或产生您要添加的内容。这有什么特别的原因吗?这会在不同的架构上发生变化,还是我可以依赖这种能力?

DB<1> print none + 1

DB<2> print 1 + none
1

只是对于那些好奇的人,这就是我使用它的方式

foreach (@someArray) {
    unless ($someHash{$_}++) {
        $someHash{$_} = 1;
    }
}

作为减少

foreach (@someArray) {
    if (exists $someHash{$_}) {
        $someHash{$_}++;
    } else {
        $someHash{$_} = 1;
    }
}
4

1 回答 1

7

你没有做你认为你正在做的事情。这两种说法:

print none + 1
print 1 + none

并不像你想象的那么简单。因为您关闭了警告,所以您不知道它们的作用。让我们在命令提示符下尝试一下,打开警告(-w开关):

$ perl -lwe'print none + 1'
Unquoted string "none" may clash with future reserved word at -e line 1.
Name "main::none" used only once: possible typo at -e line 1.
print() on unopened filehandle none at -e line 1.

$ perl -lwe'print 1 + none'
Unquoted string "none" may clash with future reserved word at -e line 1.
Argument "none" isn't numeric in addition (+) at -e line 1.
1

在第一种情况下,none是一个裸字,被解释为一个文件句柄,并且 print 语句失败,因为我们从未打开具有该名称的文件句柄。在第二种情况下,裸字none被解释为一个字符串,它被加法运算符转换为一个数字+,这个数字将是零0

您可以通过为第一种情况提供特定的文件句柄来进一步澄清这一点:

$ perl -lwe'print STDOUT none + 1'
Unquoted string "none" may clash with future reserved word at -e line 1.
Argument "none" isn't numeric in addition (+) at -e line 1.
1

none + 1这表明和之间没有真正的区别1 + none

于 2013-09-26T16:37:24.953 回答