【问题标题】:Reference a Perl Module that creates a hash in another Perl Module file that sets the hash equal to that hash引用在另一个 Perl 模块文件中创建散列的 Perl 模块,该文件将散列设置为等于该散列
【发布时间】:2019-10-26 09:19:01
【问题描述】:

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

如果 File_A.pm 使用 if(-r '/some/dir/here/File_A.pm' ) 否则它将使用 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 不知何故变得不可读。

【问题讨论】:

    标签: perl hash package perl-module exporter


    【解决方案1】:

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

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

    【讨论】:

    • 嗯,这是一个我没有考虑过的角度。如果我在外部使用 XML 文件。我将如何引用它并将其解析为 perl 哈希?
    • 你可以问一个新问题,好吧,一个新问题:-)
    • 好的,将 make 转到我的原始帖子。我的问题是循环设置 %machines 哈希等于外部 pm 的 %machine 哈希的正确方法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 2013-07-19
    • 2013-05-09
    • 2016-09-08
    相关资源
    最近更新 更多