以下两个 Perl 变量声明有什么区别?
my $foo = 'bar' if 0;
my $baz;
$baz = 'qux' if 0;
当它们出现在循环的顶部时,差异是显着的。例如:
use warnings;
use strict;
foreach my $n (0,1){
my $foo = 'bar' if 0;
print defined $foo ? "defined\n" : "undefined\n";
$foo = 'bar';
print defined $foo ? "defined\n" : "undefined\n";
}
print "==\n";
foreach my $m (0,1){
my $baz;
$baz = 'qux' if 0;
print defined $baz ? "defined\n" : "undefined\n";
$baz = 'qux';
print defined $baz ? "defined\n" : "undefined\n";
}
结果是
undefined
defined
defined
defined
==
undefined
defined
undefined
defined
似乎if 0
失败了,所以foo
永远不会重新初始化为undef
. 在这种情况下,它是如何首先声明的?