How to “use” multiple modules with one “use”?

前端 未结 3 1905
遇见更好的自我
遇见更好的自我 2020-12-09 19:18

I want use some packages and some pragmas in all my programs, like:

use 5.014;
use warnings;
use autodie;
use My::ModuleA::Something;
use ModuleB qw(Func1 Fu         


        
相关标签:
3条回答
  • 2020-12-09 19:42

    I'd go with this:

    package My::Common;
    use 5.14.0;
    use strict;
    use warnings;
    use autodie;
    use Carp qw(carp croak cluck);
    
    sub import {
        my $caller = caller;
        feature->import(':5.14');
        # feature->import('say');
        strict->import;
        warnings->import;
        ## autodie->import; # <-- Won't affect the caller side - see my edit.
        {
            no strict 'refs';
            for my $method (qw/carp croak cluck/) {
                *{"$caller\::$method"} = __PACKAGE__->can($method);
            }
        }
    }
    
    1;
    

    Please correct me if I'm wrong, or there's a better way.


    EDIT:

    Sorry, I was wrong in using autodie->import...

    This one should work, but it assumes that you always call My::Common from the main package:

    package My::Common;
    # ...
    sub import {
        # ...
        strict->import;
        warnings->import;
        {
            package main;
            autodie->import;
        }
        # ...
    }
    

    So, of course, it's much safer and simpler to add a use autodie; to each script:

    use My::Common;
    use autodie;
    # ...
    
    0 讨论(0)
  • 2020-12-09 19:52

    I've just noticed a module called rig in CPAN. Try it out.

    0 讨论(0)
  • 2020-12-09 20:07

    It's actually fairly simple, if you override your "common" module's import method. See the source of chromatic's Modern::Perl module for an example of exporting pragmas.

    For re-exporting things defined in other modules, I seem to recall that $export_to_level (see the Exporter docs, although it's not explained all that clearly) should do that, although I can't find any good examples at the moment. Another option would be Pollute::persistent, although I haven't used it, don't know anyone else who's used it, and can't say how stable/solid it's likely to be. If it works, though, it's probably the quickest and easiest option.

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