我们可以使用没有前缀的 perl 包变量,范围只在那个包中吗?

1 perl scope package

我的实际代码与此类似。

package DEF;
use warnings;
use strict;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw($STR);

our ($STR);

$STR = "bin";

1;
Run Code Online (Sandbox Code Playgroud)

包 DEF 定义了 $STR 并将其导出,以便其他人可以使用它。我可以在其他包的函数中使用 $STR 而没有任何问题。

package A;
use warnings;
use strict;
use DEF;
use File::Spec::Functions;

$var=catfile($STR,"abc","def");

sub fun{
  print($var,"\n");
}   

sub fun1{
  print($STR,"\n");
}

sub fun3{
  fun();
  fun1();
}
fun3();
1;
Run Code Online (Sandbox Code Playgroud)

我想在包中定义一个变量,可以在包的所有函数中使用,但不能在包外使用。我不想在使用变量时使用任何前缀,也不想在每个函数中定义变量。

声明变量 withour使其可以在包外访问。上面的代码没有按预期打印变量值。

当我使用my $var输出时

abc/def
bin
Run Code Online (Sandbox Code Playgroud)

但预期的输出是

bin/abc/def
bin
Run Code Online (Sandbox Code Playgroud)

ike*_*ami 5

根据定义,包变量是全局的(随处可见)。为什么不使用my变量?

package SomePkg;

use warnings;
use strict;

my $var = "abc";

sub get_var {
   return $var;
}   

1;
Run Code Online (Sandbox Code Playgroud)

它只会在相同的词法范围内可见,所以从它的声明到文件的末尾。


关于问题的更新,您对获得的输出的声明是错误的。

首先,让我们在my var;.

package SomePkg;

use warnings;
use strict;

my $var = "abc";

sub get_var {
   return $var;
}   

1;
Run Code Online (Sandbox Code Playgroud)

这是实际产生的输出:

$ diff -U 0 A.pm{~,}
--- A.pm~       2020-05-13 15:34:34.110807442 -0700
+++ A.pm        2020-05-13 15:29:17.514556346 -0700
@@ -7 +7 @@
-$var=catfile($STR,"abc","def");
+my $var=catfile($STR,"abc","def");
Run Code Online (Sandbox Code Playgroud)

让我们解决这些问题:

$ perl -Mlib=. -e'use A;'
Global symbol "@ISA" requires explicit package name (did you forget to declare "my @ISA"?) at DEF.pm line 5.
Global symbol "@EXPORT" requires explicit package name (did you forget to declare "my @EXPORT"?) at DEF.pm line 6.
Compilation failed in require at A.pm line 4.
BEGIN failed--compilation aborted at A.pm line 4.
Compilation failed in require at -e line 1.
BEGIN failed--compilation aborted at -e line 1.
Run Code Online (Sandbox Code Playgroud)

现在程序按预期工作:

$ diff -U 0 DEF.pm{~,}
--- DEF.pm~     2020-05-13 15:31:16.070648821 -0700
+++ DEF.pm      2020-05-13 15:31:19.006651138 -0700
@@ -5,2 +5,2 @@
-@ISA = qw(Exporter);
-@EXPORT = qw($STR);
+our @ISA = qw(Exporter);
+our @EXPORT = qw($STR);
Run Code Online (Sandbox Code Playgroud)

如您所见,没有问题my