我通过 do hash.pl 命令从另一个文件中使用哈希。
#!/usr/bin/perl
use feature say;
use strict;
my $givenrepo = "repopo";
my $givenbranch = "master";
do 'hash.pl';
if (exists $REPOS{$givenrepo}) {
say "herewego!";
if ($givenbranch eq $REPOS{$givenrepo}{branch}) {
say "the branch is same too!";
say "IT is $REPOS{$givenrepo}{branch}";
}
}
hash.pl 文件的内容:
our %REPOS = (
"aaa" => {
"branch" => "master",
"server" => "http://aaa",
"job" => "aaa",
},
"bbb" => {
"branch" => "master",
"server" => "http://bbb",
"job" => "bbb",
},
"ccc" => {
"branch" => "master",
"server" => "http://ccc",
"job" => "ccc",
},
};
我收到错误:
Global symbol "%REPOS" requires explicit package name (did you forget to declare "my %REPOS"?) at main.pl line 15.
Global symbol "%REPOS" requires explicit package name (did you forget to declare "my %REPOS"?) at main.pl line 17.
Global symbol "%REPOS" requires explicit package name (did you forget to declare "my %REPOS"?) at main.pl line 19.
它没有使用严格,但我真的无法理解,我做错了什么?我从另一个文件中获取此变量,但它被声明为我们的那里。
答案 0 :(得分:2)
use strict
不允许您使用外部文件中的包变量,其原因与
use strict;
{
our $X =1;
}
# our $X;
print $X;
在某些内部词法范围中定义的包变量受strict
的约束,因此您需要再次声明它才能在该范围之外使用它。
但是你可以在词法范围之前声明它,
use strict;
our $X;
{
$X =1;
}
print $X;
让strict
没有投诉。
如果您想使用do
获取一些外部配置,那么您将更好地参考
hash.pl =>
{
val => 44,
};
主脚本,
my $REPOS = do 'hash.pl';
.. exists $REPOS->{$givenrepo}