代码之家  ›  专栏  ›  技术社区  ›  Ross Rogers

在Perl中,如何从库导入哈希?

  •  2
  • Ross Rogers  · 技术社区  · 16 年前

    我有个档案 revs.pm

    my %vers = ( foo => "bar" );
    

    另一个文件是 importer.pl :

    use revs;
    

    如何访问 %vers 进口商.pl ?

    3 回复  |  直到 16 年前
        1
  •  13
  •   Mikael S    16 年前

    创建适当的模块并更改 my 关键字到 our

    # revs.pm
    package revs;
    
    our %vers = ( foo => "bar" );
    
    1; # Perl modules need to return a boolean "true" value.
    
    # importer.pl
    use revs;
    
    print $revs::vers{foo} . "\n";
    
        2
  •  9
  •   toolic    16 年前

    另一个传统的方法是使用 Exporter 在您的 package ,并导出变量:

    package revs;
    use strict;
    use warnings;
    require Exporter;
    our @ISA    = qw(Exporter);
    our @EXPORT = qw(%vers);
    our %vers   = (foo=>'bar');
    1;
    

    这避免了在引用中的变量时必须使用包名称 importer.pl

    use strict;
    use warnings;
    use Data::Dumper;
    use revs;
    print Dumper(\%vers);
    

    一个缺点是必须确保变量名是唯一的,以避免名称冲突。

        3
  •  6
  •   jrockway    16 年前

    或者,你不能把程序的一部分和

    package Foo;
    use MyApp::Versions qw(%versions); # i'm going to pretend that you didn't call the module "revs".
    
    some_function {
        while(my ($k, $v) = each %versions){
           return if $some_condition;
        }
    }
    

    然后在其他模块中:

    package Bar;
    use MyApp::Versions qw(%versions);
    
    some_other_function {
        while(my ($k, $v) = each %versions){
           print "$k => $v\n";
        }
    }
    

    然后使用两个模块:

    use Foo;
    use Bar;
    
    some_other_function;
    some_function;
    some_other_function;
    

    取决于 $some_condition 每次打电话都有结果。祝你调试愉快(这是 更像是一个 each 你不是有意的,这很容易破坏你的程序。)

    更改硬编码时重写Foo和Bar也是一种痛苦

    所以真正的解决方案是设计一个合适的API,并将其导出 而不是整个变量:

    package MyApp::Versions;
    use strict;
    use Carp qw(confess);
    use Sub::Exporter -setup => {
        exports => ['get_component_version'],
    };
    
    my %component_versions = ( foo => 42 ); # yes, "my", not "our".
    
    sub get_component_version {
        my ($component) = @_;
        return $component_versions{$component} ||
            confess "No component $component!"
    }
    
    1;
    

    现在您的模块更易于使用:

    package Foo;
    use MyApp::Versions qw(get_component_version);
    
    sub some_function {
        die 'your foo is too old'
            unless get_component_version('foo') >= 69;
    
        return FooComponent->oh_hai;
    }
    

    现在有些函数不能打乱另一些函数,当你 更改get\u组件的实现\u版本,剩下的

    推荐文章