Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Perl 包变量声明问题_Perl_Variables_Package_Declaration - Fatal编程技术网

Perl 包变量声明问题

Perl 包变量声明问题,perl,variables,package,declaration,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; } perl中的变量默认为全局变量,不管它们是否在模块中声明。“my”、“local”和“our”关键字以不

作为包“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;
}  


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

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


有关“我们的”关键字的官方文档,请参阅。

始终启用和。这些杂注帮助您捕获许多简单的错误和打字错误

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

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;
}
有关使用导出编写模块的最佳实践,请参见


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

这并不准确
$c
是一个全局包(
$Test::Test::c
),包含或不包含
我们的
,包内的任何人都可以使用该名称访问它。但是,启用了
严格的“vars”
后,即使在
Test::Test
中,也不能将其称为
$c
,除非使用
use vars
创建异常或使用
our
创建词法别名
my
local
当然做了完全不同的事情。另请参见进一步解释
我们的
到底做了什么,它与
使用变量有什么不同,以及为什么它不仅仅意味着“在这个包中可见”。是的,“严格使用”和“我们的”的结合才是重要的。使用严格的力,程序员声明变量,从而考虑范围。
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;
}