在没有警告的情况下可以使用未初始化/未定义的变量的情况如何?
解决方法
>布尔测试
>递增或递减未定义的值
>附加到未定义的值
>自动化
>其他mutators
布尔测试
The number
0
,the strings'0'
and''
,the empty list()
,and 07001 are all false in a boolean context. All other values are true.
由于未定义的值为false,以下程序
#! /usr/bin/perl use warnings; my $var; print "A\n" if $var; $var && print "B\n"; $var and print "C\n"; print "D\n" if !$var; print "E\n" if not $var; $var or print "F\n"; $var || print "G\n";
输出D到G,没有警告.
递增或递减未定义的值
如果您的代码将递增或递减至少一次,则不需要将标量显式初始化为零:
#! /usr/bin/perl use warnings; my $i; ++$i while "aaba" =~ /a/g; print $i,"\n";
附加到未定义的值
与隐含的零类似,如果你至少要附加一次,就不需要明确地将标量初始化为空字符串:
#! /usr/bin/perl use warnings; use strict; my $str; for (<*>) { $str .= substr $_,1; } print $str,"\n";
自动激活
一个例子是“自动化”.从Wikipedia article:
Autovivification is a distinguishing feature of the Perl programming language involving the dynamic creation of data structures. Autovivification is the automatic creation of a variable reference when an undefined value is dereferenced. In other words,Perl autovivification allows a programmer to refer to a structured variable,and arbitrary sub-elements of that structured variable,without expressly declaring the existence of the variable and its complete structure beforehand.
例如:
#! /usr/bin/perl use warnings; my %foo; ++$foo{bar}{baz}{quux}; use Data::Dumper; $Data::Dumper::Indent = 1; print Dumper \%foo;
即使我们没有明确地初始化中间密钥,Perl负责脚手架:
$VAR1 = { 'bar' => { 'baz' => { 'quux' => '1' } } };
my %foo; $foo{bar} = {}; $foo{bar}{baz} = {}; ++$foo{bar}{baz}{quux}; # finally!
不要将自动化与其可以产生的未定义值混淆.例如与
#! /usr/bin/perl use warnings; my %foo; print $foo{bar}{baz}{quux},"\n"; use Data::Dumper; $Data::Dumper::Indent = 1; print Dumper \%foo;
我们得到
Use of uninitialized value in print at ./prog.pl line 6. $VAR1 = { 'bar' => { 'baz' => {} } };
请注意,中间密钥自动修复.
自动化的其他例子:
>引用数组
my $a; push @$a => "foo";
>引用标量
my $s; ++$$s;
>引用哈希
my $h; $h->{foo} = "bar";
my $code; $code->("Do what I need please!");
其他mutators
In an answer to a similar question,ysth报道
Certain operators deliberately omit the “uninitialized” warning for your convenience because they are commonly used in situations where a 0 or “” default value for the left or only operand makes sense.
These are:
++
and--
(either pre- or post-),+=
,-=
,.=
,|=
,^=
,&&=
,||=
.
被定义为“或”// =愉快地突变未定义的值而不发出警告.