且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Perl何时自动初始化变量?

更新时间:2023-11-10 20:53:40

+运算符会同时评估左侧的形式和右侧的形式,然后返回两者的总和.哈希调用评估没有看到任何特殊的上下文.

The + operator evaluates both the form to the left and the form to the right of it, then returns the sum of both. The hash call evaluation does not see any special context.

++运算符内置了一些特殊的魔术.在perlop联机帮助页中对++运算符进行了引用:

The ++ operator has some special magic built in. Quoting from the perlop manpage, regarding the ++ operator:

"undef"始终被视为数字,尤其是在递增之前将其更改为0(这样,undef值的后递增将返回0而不是"undef").

"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").

edit :要详细说明它们之间的区别,++会在适当的位置更改值,而+只是将其参数作为输入.当+看到一个未定义的值时,通常会出问题,但是对于++,您的哈希操作示例非常典型-用户希望将undef视为0,而不必每次都进行检查和初始化.因此,以这种方式对待这些运算符似乎很有意义.

edit: To elaborate on the difference, ++ changes the value in place, while + just takes its arguments as input. When + sees an undefined value, typically something has gone wrong, but for ++, your hash manipulation example is very typical -- the user wants to treat undef as 0, instead of having to check and initialize everytime. So it seems that it makes sense to treat these operators this way.