Perl 使用require访问全局变量的值?

Perl 使用require访问全局变量的值?,perl,Perl,是否可以使用require访问另一个perl脚本中声明的全局变量的值 例如 Config.pl #!/usr/bin/perl use warnings; use strict; our $test = "stackoverflow" Main.pl #!/usr/bin/perl use warnings; use stricts; require "Config.pl" print "$test\n"; print "$config::test\n"; 当然。你所建议的方式几乎奏效

是否可以使用require访问另一个perl脚本中声明的全局变量的值

例如

Config.pl

#!/usr/bin/perl
use warnings;
use strict;

our $test = "stackoverflow"
Main.pl

#!/usr/bin/perl
use warnings;
use stricts;

require "Config.pl"

print "$test\n";
print "$config::test\n";

当然。你所建议的方式几乎奏效。尝试:

Config.pl

use warnings;
use strict;

our $test = "stackoverflow";
use strict;
use warnings;
use MyConfig qw( :ALL );
print "$test\n";
主要节目是:

#!/usr/bin/perl
use warnings;
use strict;  

require "Config.pl";

our $test;

print "$test\n";

调用
require
时,文件将在与调用方相同的命名空间中执行。因此,如果没有任何名称空间或
my
声明,任何分配的变量都将是全局变量,并且对脚本可见。

您需要通过编写声明
Main.pl
中的变量
$test

our $test;

正如您在
Config.pl
中所做的那样。然后一切都会按照您的预期工作。

最好使用模块:

MyConfig.pm
:(已经有一个名为“Config”的核心包了。)

main.pl

use warnings;
use strict;

our $test = "stackoverflow";
use strict;
use warnings;
use MyConfig qw( :ALL );
print "$test\n";

use vars
已被宣布为过时。它已被
我们的
@Borodin所取代,
使用变量
并不是过时的,尽管文档与此相反。@ikegami:你能用某种方式备份一下吗?使用
我们的
并具有相同的效果肯定更笨拙。@Borodin,不,它没有相同的效果。你和修补vars.pm的人都认为自己笨手笨脚,但并不是所有的搬运工都这么认为。我想应该是“打包MyConfig;”。@Bill Ruppert,ack!,谢谢谈论破坏我自己的观点。固定的。