嗨,我是 Perl 编程的新手,我刚刚在 Perl 中遇到了这些类型的变量: 包和词法
到目前为止,我了解到这是一个包变量:
$Santa::Helper::Reindeer::Rudolph::nose
所以我的问题是,Perl 怎么知道我指的是$nose, or @nose or %nose那个包里面的东西?
如果我用名称声明另一个变量(词法变量),这也有效吗
$nose or @nose or %nose使用我的:
例子:my $nose;
$Santa::Helper::Reindeer::Rudolph::nose
是$nose
@Santa::Helper::Reindeer::Rudolph::nose
是@nose
如果包通过声明使用词法范围的变量our $nose,并且您my $nose在使用该包的代码中声明,您将破坏它。如果你use strict和use warnings(你总是应该这样做)那么它会在发生这种情况时给你一个警告:"my" variable $nose masks earlier declaration in same scope. 如果包通过声明使用私有变量my $nose,那么您也可以my $nose在代码中声明,并且包的$nose将不受影响。
当在 范围内时package Santa::Helper::Reindeer::Rudolph;,
$nose简称$Santa::Helper::Reindeer::Rudolph::nose
和
@nose是 的缩写@Santa::Helper::Reindeer::Rudolph::nose。
也就是说,除非您创建了一个范围内的词法变量(使用my $nose;or our $nose;)。如果是这样,那么您最后声明的变量就是使用的变量。
package Santa::Helper::Reindeer::Rudolph;
$Santa::Helper::Reindeer::Rudolph::nose = 123;
print "$nose\n"; # 123
my $nose = 456; # Creates new lexical var
print "$Santa::Helper::Reindeer::Rudolph::nose\n"; # 123
print "$nose\n"; # 456
{
my $nose = 789; # Creates new lexical var
print "$nose\n"; # 789
}
print "$nose\n"; # 456
our $nose; # Creates lexical var aliased to $S::H::R::R::nose
print "$nose\n"; # 123