in reply to Most effective way to dynamically load a module?

Simpler answer. Change your eval to eval "use $class ()"; and drop the can.

Check the documentation, use already checks whether a class is loaded and doesn't reload it the second time. That check is more efficient than calling can. However use will call import. Since you don't need the calls to import, the empty parens can be used to get rid of them.

Replies are listed 'Best First'.
Re^2: Most effective way to dynamically load a module?
by BerntB (Deacon) on Aug 22, 2006 at 04:12 UTC
    Yes, but isn't eval expensive? It has to start up the Perl parser, etc.
      Define expensive.

      eval isn't free, but it doesn't cost that much. In any case this is all micro-optimization that is unlikely to matter much.

        "expensive" here means that I am nervous about this part of the code. :-)

        I think this bit of code (together with unpacking of objects) are in the critical path.

        Hmmm... to compile a single statement with one parameter shouldn't be much more than lex:ing a couple of strings and doing a jump in a parser's jump table, then mallocing a bit memory for the minimal parse tree and probably copying the parameter.

        OK, my instinctive fear of eval might be wrong, here. (-: You can take the compiler from the old C programmer but you can never stop him doing premature optimizations? :-)

      If you have to do it at runtime, just use require. It won't call import, and it won't load a module if it's already loaded.
        Using require is fine but then you have to manually convert between class names and file names yourself. Which means that you have to translate Module::Name to Module/Name.pm.

        Not hard. But requires extra code.