Perl 关于 use strict 的用法

什么场合要用 use strict

当你的程序有一定的行数时,尤其是在一页放不下时,或者是你找不到发生错误的原因时。

为什么要用 use strict?

众多的原因之一是帮你寻找因为错误拼写造成的错误。比如错误使用了'$recieve_date' 变量,但实际上你在程序中已声明的是 '$receive_date' 变量,这个错误就很难发现。同样,use strict 迫使你把变量的范围缩到最小,使你不必担心同名变量在程序的其它部份发生不良作用。(尽管这是 my 的功能,但是如果你使用 use strict 的话,它会强迫你用 my 声明变量,来达到上述目的)。

用 use strict 麻烦吗?

不麻烦,只要在你的脚本的开始加上11个字符而已!(use strict;), 另外在整个程序中用my 声明变量。

 

不错,那我怎么用 use strict 呢?

在你的脚本的开头 '#!/usr/local/bin/perl' 后面加上这句就行。

use strict;

得,程序出错了,我该怎么办?

常见的错误信息一般如下:

Global symbol "$xxx" requires explicit package name at ./tst line 5.

这就是需要我们马上去解决的错误。(如果出现类似于 'Server Error' 之类的错误,请检查一下你的 web 服务器上的 error logs, 或用CGI::Carp包。 )

任何时候,当你要声明一个变量时,都要把 'my' 放在前面。例如:

# 把这段代码:
$string = "hello world";
@array = qw(ABC DEF);
%hash = (A=>1, B=>2);

# 改成:
my $string = "hello world";
my @array = qw(ABC DEF);
my %hash = (A=>1, B=>2);

# 把这段代码:
# '$name' is global here
foreach $name (@names) {
 print "Name: $name\n";
}

# 改成:
foreach my $name (@names) {
 # Now '$name' only exists in this block
 print "Name: $name\n";
}

# 把这段代码:
# 同样, '$digit' 在这里是全局变量
foreach $digit (@digits) {
 $number = 10== $number + $digit;
}
print "Number: $number\n";

# 改成: (外层的变量('$number')
# 将在外层声明):
my $number = 0;
foreach my $digit (@digits)
 # 现在'$digit' 仅仅在这个代码块里存在
 $number = 10== $number + $digit;
}
print "Number: $number\n";

# 把这段代码:
sub my_sub {
 ($arg1, $arg2) = @_;
 print "Arg1: $arg1 Arg2: $arg2\n";
}

# 改成:
sub my_sub {
 my ($arg1, $arg2) = @_;
 print "Arg1: $arg1 Arg2: $arg2\n";
}

# 下面的代码好像在用 DBI 嘛?一样要改!:
$sth->bind_columns(\$field1, \$field2);
while ($sth->fetch) {
 print "F1: $field1 F2: $field2\n";
}

# 改成:
$sth->bind_columns(\my ($field1, $field2));
while ($sth->fetch) {
 print "F1: $field1 F2: $field2\n";
}

这也太麻烦了吧。懒惰不是 Perl 文化中的美德吗?

当然,懒惰是我们的美德。因为你会发现使用 use strict 之后,我们就不必花太多的时间自己去查找 use strict 可以找到的很多简单错误。

那 warnings 又是什么?

哦,对了。在 Perl 5.6 及以后的版本里,我们可以在写 'use strict;' 的位置旁写 'use warnings;':

use warnings;

在 Perl 5.6 版之前(或者为了不同 Perl 版本间的兼容 ),你可以用命令行参数 '#!/usr/bin/perl -w'。还有一种办法是设置

$^W

变量(不过,如果

$^W

不在BEGIN{}程序块里的话,就没办法截取编译时的错误提示,所以一般我们用 '-w'):

#!/usr/local/bin/perl -w

# 或者
$^W = 1;
# 或者
BEGIN { $^W = 1 }

如果你确定不用 warnings,你可以限制它的使用范围,如:

# 把这段代码:
sub add_two_numbers_which_might_be_undef {
 $_[0] + $_[1];
}

# 根据Perl 的版本不同改成下面的样子:
# 1
sub add_two_numbers_which_might_be_undef {
 # 参见 'perldoc perllexwarn' 
 # 因为最好是只在你希望的地方禁止掉warning
 no warnings "uninitialized";
 $_[0] + $_[1];
}

# 2
sub add_two_numbers_which_might_be_undef {
 local $^W;
 $_[0] + $_[1];
}

或者,你应像前面例子中声明 '$number'一样初始化变量。

你还可以参阅Ovid的妙文use strict' is not Perl

以及(Wog指出的):Use strict warnings and diagnosticsUse strict warnings and diagnostics or die.

okay,现在你应该没什么借口不用 use strict 或 use warnings 了吧,它使我们大家生活可以轻松一些:)

posted @ 2013-12-03 13:53  xuefenhu  阅读(6362)  评论(0编辑  收藏  举报