假如你在编写某个函数,并且你想要它有私有变量,就必须使用my来申明变量。假如忘记了,会发生什么事? sub function { $x = 42; # Oops, should have been my $x = 42. }
在这种情形下,你的函数修改了全局包变量$x。假如你在其他地方要用到那个包变量,那对程序将是灾难。
最近版本的perl有针对这点的保护选项,你可以激活它。假如放置:
use strict 'vars';
在程序的顶部,perl将要求包变量有明确的包限定词。$x=42里的$x没有这样的限定词,所以程序甚至不会通过编译;代替的,编译器会异常中断,并输出如下错误消息:
Global symbol "$x" requires explicit package name at ...
假如你希望$x是个私有my变量,你可以回头增加my。假如你确实想使用全局包变量,你能回头改变它为:
$main::x = 42;
或其他相应的包。
use strict还有其他的检测选项,请看perldoc strict的更多细节。
现在假设你在编写Algorithms::KnuthBendix模块,你想使用strict vars保护模式,但假如任何时候你需要一遍又一遍的敲入$Algorithms::KnuthBendix::Error,你会觉得很烦。
你可以告诉strict vars生成一个例外:
package Algorithms::KnuthBendix; use vars '$Error';
这样就在你使用短名字$Error时,避免了包变量$Algorithms::KnuthBendix::Error导致的strict vars失败。
如下写法,也可以在某个代码块里关闭strict vars:
{ no strict 'vars'; # strict vars is off for the rest of the block. } |