包变量声明问题

时间:2010-11-10 06:53:37

标签: perl variables package declaration

作为这两个软件包版本之间的“Test :: Test”软件包的用户,我有什么不同(如果有的话):

Test::Test;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(hello);
use strict; use warnings;

our $c = 3;
sub hello {
    print "$_\n" for 0 .. $c;
}  

Test::Test;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(hello);

$c = 3;
sub hello {
    print "$_\n" for 0 .. $c;
}

3 个答案:

答案 0 :(得分:4)

始终启用strictwarnings是一种很好的做法。这些编译指示可以帮助您捕获许多简单的错误和拼写错误。

这两个样本是等价的。但第一个是首选,因为它显式使用$c声明全局变量our并启用限制和警告。

答案 1 :(得分:3)

FWIW,正确的编写此模块的方式是这样的:

package Test::Test;
use strict;
use warnings;

use Exporter 'import';  # gives you the import method directly
our @EXPORT = qw(hello);

my $c = 3;
sub hello {
    print "$_\n" for 0 .. $c;
}

有关使用导出编写模块的最佳实践,请参阅perldoc Exporter

我还建议更改此包的名称,因为Test :: namespace已被核心模块和CPAN发行版使用。

答案 2 :(得分:1)

perl中的变量默认为全局变量,无论它们是否在模块中声明。 “我的”,“本地”和“我们的”关键字以不同的方式定义变量。在您的示例中,“我们的$ c”将变量的可见性限制在您的包中(除非您选择导出它,但这是另一个故事)。

因此,对于后一个示例,访问和修改$ c的任何其他代码也会影响您的代码。

有关“我们的”关键字的官方文档,请参阅http://perldoc.perl.org/functions/our.html