Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to "use" a single file that in turn uses multiple others in Perl?

Tags:

module

perl

I'd like to create several modules that will be used in nearly all scripts and modules in my project. These could be used in each of my scripts like so:

#!/usr/bin/perl

use Foo::Bar;
use Foo::Baz;
use Foo::Qux;
use Foo::Quux;

# Potentially many more.

Is it possible to move all these use statements to a new module Foo::Corge and then only have to use Foo::Corge in each of my scripts and modules?

like image 454
cowgod Avatar asked Jan 13 '09 02:01

cowgod


2 Answers

Something like this should work:

http://mail.pm.org/pipermail/chicago-talk/2008-March/004829.html

Basically, create your package with lots of modules:

package Lots::Of::Modules;
use strict; # strictly optional, really

# These are the modules we want everywhere we say "use Lots::Of::Modules".
# Any exports are re-imported to the module that says "use Lots::Of::Modules"
use Carp qw/confess cluck/;
use Path::Class qw/file dir/;
...

sub import {
    my $caller = caller;
    my $class  = shift;

    no strict;
    *{ $caller. '::'. $_ } = \*{ $class. '::'. $_ }
       for grep { !/(?:BEGIN|import)/ } keys %{ $class. '::' };
}

Then use Lots::Of::Modules elsewhere;

use Lots::Of::Modules;
confess 'OH NOES';
like image 135
jrockway Avatar answered Nov 16 '22 01:11

jrockway


Yes, it is possible, but no, you shouldn't do it.

I just spent two weeks to get rid of a module that did nothing but use other modules. I guess this module started out simple and innocent. But over the years it grew into a huge beast with lots and lots of use-statements, most of which weren't needed for any given run of our webapp. Finally, it took some 20 seconds just to 'use' that module. And it supported lazy copy-and-paste module creation.

So again: you may regret that step in a couple of months or years. And what do you get on the plus side? You saved typing a couple of lines in a couple of modules. Big deal.

like image 34
innaM Avatar answered Nov 16 '22 00:11

innaM