How do I group my package imports into a single custom package?

早过忘川 提交于 2019-12-05 08:21:42

Have a look at ToolSet, which does all the dirty import work for you.

Usage example from pod:

Creating a ToolSet:

# My/Tools.pm
package My::Tools;

use base 'ToolSet'; 

ToolSet->use_pragma( 'strict' );
ToolSet->use_pragma( 'warnings' );
ToolSet->use_pragma( qw/feature say switch/ ); # perl 5.10

# define exports from other modules
ToolSet->export(
 'Carp'          => undef,       # get the defaults
 'Scalar::Util'  => 'refaddr',   # or a specific list
);

# define exports from this module
our @EXPORT = qw( shout );
sub shout { print uc shift };

1; # modules must return true

Using a ToolSet:

use My::Tools;

# strict is on
# warnings are on
# Carp and refaddr are imported

carp "We can carp!";
print refaddr [];
shout "We can shout, too!";

/I3az/

This is harder than you expect.

  • For pragmas like strict and warnings you can pass them through.

  • For modules that don't export functions such as object oriented ones, it will work.

  • However for modules that export by default, like Data::Dumper (it gives you the Dumper() function in the package of the caller), it is trickier.

You can make it work by telling Exporter that there is an extra layer of magic:

So you could do:

package my_packages;

use strict;
use warnings;
use Data::Dumper; 
use IO::Socket;


$Exporter::ExportLevel = 1; # Tell Exporter to export to the caller

sub import {

    # Enable this in the callers package

    strict->import;       # pragma in caller
    warnings->import;     # pragma in caller
    Data::Dumper->import; # Adds Dumper() to caller

    # No need for IO::Socket since it's OO.

    return 1;
}

1;

For three modules, this hardly seems to be worth it.

See this:

package Foo;

use warnings;

sub import {
    warnings->import;
}

1;

And now:

$ perl <<CUT
> use Foo;
> \$a = 5; # backslash just to keep the $ from being eaten by shell
> CUT
Name "main::a" used only once: possible typo at - line 2.

Taken from Modern::Perl.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!