perl - 'uninitialized value' 警告的解释

标签 perl

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

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

perl -we '$c += 3' 不会提示未初始化的值?

更新

文档或诸如“Perl 最佳实践”之类的书籍是否提到了这种行为?

最佳答案

我认为 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.

关于perl - 'uninitialized value' 警告的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23767321/

相关文章:

macos - 苹果操作系统 :/usr/bin/env: bad interpreter: Operation not permitted

perl - 只需要在一个文件中匹配一个模式出现一次

linux - Linux 的 Perl 脚本中的权限错误

javascript - 我需要进行 Ajax 调用并显示数据库表的内容,我正在使用 Perl CGI 并尝试通过 javaScript 调用 Perl 脚本

perl - B::Lint 和 Perl::Critic 用于静态代码分析

linux - 执行 bash 的 Perl 转义参数

perl - 如何检查 Perl 中是否已创建对象?

perl - 为什么 Perl 变量需要以 $、%、@(符号)开头?

perl - 用于处理 CSV 文件、聚合分布在多个记录中的属性的 Perl 脚本

perl - 如何在 perl 5.24 中关闭 "when is experimental ..."?