damog has asked for the wisdom of the Perl Monks concerning the following question:

Hey guys. I wanna create a module that loads other modules for the script using that first module, how can I do that? Lemme clarify. What I want is to be able to do this:
# myscript.pl use SuperModuleLoader; # or whatever my $c1 = SomeClass->new; my $c2 = SomeOtherClass->new; my $mech = WWW::Mechanize->new;
without having to declare SomeClass, SomeOtherClass and all other classes in there. Basically all those classes are on a directory (but I could use some other modules too) so I tried this:
package SuperModuleLoader; sub import { my $classes = [qw/SomeClass SomeOtherClass WWW::Mechanize YourMom/]; for my $c (@$classes) { require $c; } } 1;
...but that doesn't work. Is that possible? As said, SomeClass.pm, SomeOtherClass.pm and other custom classes are right on the same directory, but some other might just be within the system-wide installation and wanna be able to initialize classes with them on my script without having to list them all in it.

Replies are listed 'Best First'.
Re: On kind of dynamic loading
by Corion (Patriarch) on Sep 25, 2010 at 08:12 UTC

    See require for how to make require load a class dynamically.

    Basically, you need to transform a class name into a (unix) path name to require. parent.pm has the code, which I'm quoting here:

    for (@modules) { s{::|'}{/}g; require "$_.pm"; # dies if the file is not found };
Re: On kind of dynamic loading
by Anonymous Monk on Sep 24, 2010 at 19:15 UTC