Perhaps you should rethink your approach, and go for require instead of use, and use an OO approach, even though you have no objects, by calling the subs as class methods. That way, you can get rid of the eval, and even have it pass strict without problem.

One problem when calling require with a variable scalar, is that the format must be different: the magic conversion you get when writing require Foo::Bar; no longer works: you have to convert 'Foo::Bar' to 'Foo/Bar.pm' yourself. So this should, basically, work:

use strict; our $module = 'Foo::Bar'; my $file = join('/', split /::/, $module) . '.pm'; require $file; $module->run();
Note that any class method ("run") you call this way, will get one extra argument prepended, in front of any of your own: the class name, the string that's currently in $module.

p.s. For reasons of sanity, I personally would prefer an extra root in front of the actual module names, for example 'MyDrivers' (bad example :-), so you actually load and run MyDrivers::Foo::Bar, if the user supplies the string 'Foo::Bar'. That way, you can make sure you can only load modules that are especially prepared to be used this way.

p.p.s. People using older perls than 5.6.0 should replace the 'our' with another appropriate solution (use vars or my), or simply not use strict :-). This has nothing to do with the functionality of the code I described here. I would think that should still work.


In reply to Re: Loading a module at runtime... by bart
in thread Loading a module at runtime... by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.