[Chicago-talk] Is there a way to simplify including multiple .pm files?

Jonathan Rockway jon-chicagotalk at jrock.us
Fri Mar 14 13:32:58 PDT 2008


* On Fri, Mar 14 2008, He Guangsheng-W16844 wrote:

> My scripts take a lot of constants, so I defined these constants in
> several ConstantVar.pm files and include them all. But more and more
> constant files coming, so I have to add one line 'use ...'  to each of
> my scripts. Is there a better way to manage this? 

How about:

   package Lots::Of::Module;

   my @modules = (
      'Carp qw/carp confess/',
      'Path::Class qw/file dir/',
   );

   sub import {
      my $caller = caller;
      eval "package $caller; use $_" for @modules;
   }

Actually... you can do this without eval:

   package Lots::Of::Modules;
   use Carp qw/confess cluck/; # modules you want to use
   use Path::Class qw/file dir/;

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

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

In both cases, you do this:

   use Lots::Of::Module;

   confess; cluck; file; dir; # these were all imported

Enjoy.

Regards,
Jonathan Rockway

-- 
print just => another => perl => hacker => if $,=$"


More information about the Chicago-talk mailing list