在 Perl 调试器中运行该程序显示$tmp
设置为空字符串,该defined
函数的计算结果为 true。这就是设置条件$a
为真的原因:
$ perl -d
Loading DB routines from perl5db.pl version 1.33
Editor support available.
Enter h or `h h' for help, or `perldoc perldebug' for more help.
use strict;
use warnings;
my $a = "init";
sub funct{
my $var;
#$var = 1;
return $var if defined $var;
}
my $tmp = funct;
$a = $tmp if defined $tmp;
print "$a\n";
__END__
main::(-:4): my $a = "init";
DB<1> x $a
0 undef
DB<2> n
main::(-:12): my $tmp = funct;
DB<2> x $a
0 'init'
DB<3> x $tmp
0 undef
DB<4> n
main::(-:14): $a = $tmp if defined $tmp;
DB<4> x $tmp
0 ''
修复,简单地说return $var
,没有if defined $var
. 这将设置$tmp
为undef