Perl: how to share the import of a large list of modules between many independent scripts?

后端 未结 5 876
梦如初夏
梦如初夏 2021-01-12 10:40

I have many standalone scripts. The only thing they share, is that they use() a large set of CPAN modules (that each export several functions). I would like to centralize th

相关标签:
5条回答
  • 2021-01-12 11:09

    Using require is the most natural way to do this. Under mod_perl you may need to modify @INC during server startup.

    0 讨论(0)
  • 2021-01-12 11:10

    Maybe you want Toolkit.

    0 讨论(0)
  • 2021-01-12 11:27

    The problem with all three of your proposed solutions is that the module may be used from another module, in which case the symbols should be exported into the useing module's package, not into main.

    bvr's solution of using caller to import things directly into that package is a major step in the right direction, but prevents the 'real' package from using use ShareableModules qw( foo bar baz); to selectively import only what it actually needs.

    Unfortunately, preserving the ability to import selectively will require you to import all relevant symbols from the underlying modules and then re-export them from ShareableModules. You can't just delegate the import to each underlying module's import method (as Modern::Perl does) because import dies if it's asked for a symbol that isn't exported by that module. If that's not an issue, though, then Modern::Perl's way of doing it is probably the cleanest and simplest option.

    0 讨论(0)
  • 2021-01-12 11:28

    Maybe more flexible than putting everything into main namespace would be to import into caller's namespace. Something like this:

    package SharedModules;
    
    sub import {
    
        my $pkg = (caller())[0];
        eval <<"EOD";
    
    package $pkg;
    
    use List::Util;
    use List::MoreUtils;
    
    EOD
    
        die $@ if $@;
    }
    
    1;
    
    0 讨论(0)
  • 2021-01-12 11:28

    File import.pl:

    require blah;  blah->import;
    require blubb; blubb->import;
    

    Skripts:

    #!/usr/bin/perl
    do 'import.pl'
    ...
    

    Patrick

    0 讨论(0)
提交回复
热议问题