为什么 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/