Perl何时自动初始化变量? [英] When does Perl auto-initialize variables?

查看:114
本文介绍了Perl何时自动初始化变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一些简单的Perl,用于计算值在数组中出现的次数.这将在没有任何警告的情况下运行.

Here is some simple Perl to count the number of times a value occurs in an array. This runs without any warnings.

use warnings;
use strict;

my @data = qw(1 1 2 3 4 5 5 5 9);
my %histogram;
foreach (@data)
{
    $histogram{$_}++;
}

将循环主体更改为

$histogram{$_} = $histogram{$_} + 1;

Perl警告另外使用未初始化的值".

Perl warns "Use of uninitialized value in addition".

幕后到底发生了什么?为什么将值作为操作数提供给++运算符而未使用+运算符初始化?

What is going on under the hood? Why is the value initialized when supplied as an operand to the ++ operator and uninitialized with the + operator?

推荐答案

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

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.

这篇关于Perl何时自动初始化变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆