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

Steven Lembark lembark at wrkhors.com
Fri Mar 14 14:49:08 PDT 2008


 > 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?
 >
 > In C, we can make one header include a lot of headers, the only need to
 > maintain changes for this one. Is that similar approach in Perl?

This will install ANY list of modules into your
caller's namespace, in this format it's intended
to walk down a list and install them from the
"Constants" namespace.

     # all of your groups of constants are in
     # Constants::Foo, etc, all of them can
     # just @EXPORT, whatever. the modules should
     # probably have an ':all' switch that exports
     # everything rather than putting it all into
     # @EXPORT but that's your call.

     package Constants::All;

     my @all_modules
     = qw
     (
         These
         Those
         Foo
         Bar
         Bletch
         Blort
     );

     sub import
     {
         my $caller  = caller;

         # discard this package. what's left on
         # the stack is a list of constant modules
         # to process or nada, which gets them all.
         #
         # note that the arguments do not include
         # the "Constants::" prefix.

         shift if $_[0] eq __PACKAGE__;

         for my $module ( @_ ? @_ : @all_modules )
         {
             substr $module, 0, 0, 'Constants::';

             # lazy: if you don't want to type a
             # bunch of source lines then let
             # Perl do it for you!

             eval "package $caller; use $module";

             # add'l checks for $@, etc, down here.
         }

         # avoid data leaks

         return
     }

     1

     __END__

-- 
Steven Lembark                                          +1 888 359 3508
Workhorse Computing                                       85-09 90th St
lembark at wrkhors.com                                 Woodhaven, NY 11421


More information about the Chicago-talk mailing list