Perl使用名称空间作为变量名称,当Perl看到::
或'
时,它使用Perl,它假定以前是包(即名称空间)名称。它类似于此错误:
use strict;
use warnings; # You're using these? Aren't you?
my $foo = "bar"
print "The magic word is $foo_for_you\n";
由于下划线是变量名的有效字符,Perl中假定你想要的变量$foo_for_you
与_for_you
附加价值不$foo
。那么,你会认为这是一个错误或功能?它是从这个有什么区别:
print "The magic word is $foobar\n"; # Whoops! my variable is $foo.
来解决这个问题是要绝对清楚地表明$foo
的方式是你的变量:
print "The magic word is " . $foo . "_for_you\n";
printf "The magic word is %s_for_you\n", $foo;
print "The magic word is ${foo}_for_you\n";
,如果你有同样的问题$foo::for::you
(或$foo'for'you
)在这种情况下,Perl正在名称空间foo::for
中寻找名为$you
的变量。你可以想像,你可以用类似的解决方案:
print "The magic word is " . $foo . "::for::you\n";
printf "The magic word is %d::for::you\n", $foo;
print "The magic word is ${foo}::for::you\n";
命名空间用来帮助保持Perl模块变量在你的程序修改变量。想象一下,在一个Perl包中调用一个函数,并突然发现你的程序中使用的变量发生了变化。
看看File::Find,你可以看到变量与连接到他们($File::Find::name
和$File::Find::dir
是两个例子)包命名空间。
总是使用'use strict;使用警告;'。这会说你打印了未定义的变量'$ word :: test'。 – ikegami