perl strict 模块简介
当程序有一定的行数时,或者是你找不到发生错误的原因时,它可以帮你寻找因为错误拼写造成的错误。比如错误使用了'$freeoa_love' 变量,但实际上你在程序中已声明的是 '$freeoa_lvoe' 变量,这个错误就很难发现。同样,use strict 迫使你把变量的范围缩到最小,使你不必担心同名变量在程序的其它部份发生不良作用(尽管这是 my 的功能,但是如果你使用 use strict 的话,它会强迫你用 my 声明变量,来达到上述目的)。命令use strict意味着所有变量必须用my来声明,裸单词必须用引号括起来,use strict语句实际上可以称为编译器命令。它能够告诉 Perl,给下列情况做上指向当前代码块或文件中的运行期错误的标志:
• 试图使用不是用my声明的变量名(不是特殊变量的名字)。
• 当函数定义尚未设置时,试图将裸单词用作函数名。
• 其他潜在的错误。
use strict包含3个部分。它们分别是:strict refs(负责管理符号引用)、strict vars(负责管理变量作用域或其本身)、strict subs(负责禁止乱用的裸字)。
strict - Perl pragma to restrict unsafe constructs(限制Perl程序不安全使用)
使用方法
use strict;
use strict "vars";
use strict "refs";
use strict "subs";
又想使用'strict'但又不想要变量作用域管理
use strict;
no strict "vars";
如果不提供导入列表,则认为所有可能的限制(这是最安全的方式操作,但有时显得过于严格)。目前,有严格约三可能的事情:"subs", "vars", and "refs"。
另外,在5.10版本后,可以载入对应的版本号的自动载入该模块(strict,warnings)。
use v5.10;
1、strict refs
This generates a runtime error if you use symbolic references (see perlref).
use strict 'refs';
$ref = \$foo;
print $$ref; # ok
$ref = "foo";
print $$ref; # runtime error; normally ok
$file = "STDOUT";
print $file "Hi!"; # error; note: no comma after $file
There is one exception to this rule:
$bar = \&{'foo'};
&$bar;
is allowed so that goto &$AUTOLOAD would not break under stricture.
2、strict vars
This generates a compile-time error if you access a variable that was neither explicitly declared (using any of my, our, state, or use vars ) nor fully qualified. (Because this is to avoid variable suicide problems and subtle dynamic scoping issues, a merely local variable isn't good enough.) See my, our, state, local, and vars.
use strict 'vars';
$X::foo = 1; # ok, fully qualified
my $foo = 10; # ok, my() var
local $baz = 9; # blows up, $baz not declared before
package Cinna;
our $bar; # Declares $bar in current package
$bar = 'HgS'; # ok, global declared via pragma
The local() generated a compile-time error because you just touched a global name without fully qualifying it.Because of their special use by sort(), the variables $a and $b are exempted from this check.
3、strict subs
This disables the poetry optimization, generating a compile-time error if you try to use a bareword identifier that's not a subroutine, unless it is a simple identifier (no colons) and that it appears in curly braces or on the left hand side of the => symbol.
use strict 'subs';
$SIG{PIPE} = Plumber; # blows up
$SIG{PIPE} = "Plumber"; # fine: quoted string is always ok
$SIG{PIPE} = \&Plumber; # preferred form
我们平常把字符串放在引号里的习惯,但是Perl默认是允许(使用)裸字——没有引号的单词——来作为字符串。会报出如下的错误提示:
Bareword "hello" not allowed while "strict subs" in use at script.pl line 3.
Execution of script.pl aborted due to compilation errors.
即便开启了use strict "subs"还是有些地方可以使用裸字。首先用户自定义的函数名就是裸字,同样在提取哈希表元素花括号里也使用了裸字,以及箭头符=>的左边也可以没有引号。
参考来源:http://perldoc.perl.org/strict.html