0

我有 2 个 perlmodule 文件(.pm)。File_A.pm 位于 /some/dir/here/File_A.pm。我有一个位于 /some/other/dir/File_B.pm 的 File_B.pm。

如果使用 if(-r '/some/dir/here/File_A.pm') 可以读取 File_A.pm,则 File_B.pm 将我的 %machines 哈希设置为等于 /some/dir/here/File_A.pm 的 %machines 否则它将使用 File_B.pm 中定义的标准哈希作为我的 %machines = ()。

我试过下面的代码

但是,这对我不起作用。

package some::other::dir::File_B;
use strict;
use vars qw(@ISA @EXPORT $VERSION);
use Cwd;
use some::dir::File_A;

use Exporter;
$VERSION = 1.0;
@ISA     = qw(Exporter);
@EXPORT =
  qw(getMachines printMachines getMachineAttributes printMachineAttributes);

if(-r '/some/dir/here/File_A.pm'){
    my %machines = do q{/some/dir/here/File_A.pm};
else{
 my %machines = (  
    "some.fqdn.com" => {
    role        => ["someRole"],
    environment => "test",
    location    => "USA",
    os          => "Ubuntu",},
    )
}
###################################
#I have getMachines, printMachines, getMachineAtrributes, and
#printMachineAttributes below here in my code
####################################

我期望逻辑使用 File_A.pm 我的 %machines 哈希,如果它是可读的,如果不使用备份我的 %machines 哈希,以防 File_A.pm 不知何故变得不可读。

4

1 回答 1

1

用my定义的词法变量的范围从声明到封闭块的末尾。第一个my %machines在“then”块中不存在,第二个在“else”块的末尾消失。

请注意,如果恶意用户可以写入 File_A,他们可以将任何代码插入其中。使用 INI 文件或 JSON、YAML、XML 或其他任何内容来填充散列会更安全。

于 2019-06-11T22:30:50.253 回答