解释'未初始化的值'警告

时间:2014-05-20 18:29:23

标签: perl

为什么perl -we '$c = $c+3'上升

Use of uninitialized value $c in addition (+) at -e line 1.

perl -we '$c += 3'不抱怨未初始化的价值?

更新

文档或像“Perl最佳实践”这样的书是否提到了这种行为?

2 个答案:

答案 0 :(得分:5)

我认为perldoc perlop有一点解释:

Assignment Operators
       "=" is the ordinary assignment operator.

       Assignment operators work as in C.  That is,

           $a += 2;

       is equivalent to

           $a = $a + 2;

       although without duplicating any side effects that dereferencing the
       lvalue might trigger, such as from tie()

使用B::Concise帮助器,我们可以看到诀窍:

$ perl -MO=Concise,-exec -e '$c += 3'
1  <0> enter 
2  <;> nextstate(main 1 -e:1) v:{
3  <#> gvsv[*c] s
4  <$> const[IV 3] s
5  <2> add[t2] vKS/2
6  <@> leave[1 ref] vKP/REFC
-e syntax OK

$ perl -MO=Concise,-exec -e '$c = $c + 3'
1  <0> enter 
2  <;> nextstate(main 1 -e:1) v:{
3  <#> gvsv[*c] s
4  <$> const[IV 3] s
5  <2> add[t3] sK/2
6  <#> gvsv[*c] s
7  <2> sassign vKS/2
8  <@> leave[1 ref] vKP/REFC
-e syntax OK

<强>更新

perldoc中搜索后,我发现此问题已记录在perlsyn中:

Declarations
       The only things you need to declare in Perl are report formats and subroutines (and sometimes not even subroutines).  A variable
       holds the undefined value ("undef") until it has been assigned a defined value, which is anything other than "undef".  When used as a
       number, "undef" is treated as 0; when used as a string, it is treated as the empty string, ""; and when used as a reference that
       isn't being assigned to, it is treated as an error.  If you enable warnings, you'll be notified of an uninitialized value whenever
       you treat "undef" as a string or a number.  Well, usually.  Boolean contexts, such as:

           my $a;
           if ($a) {}

       are exempt from warnings (because they care about truth rather than definedness).  Operators such as "++", "--", "+=", "-=", and
       ".=", that operate on undefined left values such as:

           my $a;
           $a++;

       are also always exempt from such warnings.

答案 1 :(得分:4)

因为在添加数字以外的其他内容时添加警告是有意义的,但+=非常方便不警告未定义的值。

正如Gnouc发现的那样,perlsyn中记录了这一点:

  

++, - ,+ =, - =和。=等运算符,对未定义的变量进行操作,例如:

undef $a;
$a++;
     

也始终免于此类警告。