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

Ok this may be a dumb idea but I want to try it, But Iam
going to ask everyones opinion anyways.
"What is the best way to load (use) dynamic perl modules".

I.E.
$mod = "stuff"; Junk::$mod->foo("bar");
P.S. Feel free to tell me how stupid Iam :)
P.P.S I know the above code doesnt work.

Replies are listed 'Best First'.
Re: Stupid OO question
by tye (Sage) on Aug 02, 2000 at 20:39 UTC

    Are you asking how to load a module who's name you don't know at compile time? Here are some examples:

    BEGIN { if( $^O =~ /Win32/i ) { eval 'use Win32::SerialPort qw(:ALL); 1;' or die $@; } else { eval 'use Device::SerialPort qw(:ALL); 1;' or die $@; } }

    This gets the full effect of use with symbols imported at compile time so you can use them as barewords. But doing this is only useful if you know at compile time what symbols you want to import but not what module you want to import them from. That is a pretty rare situation.

    $mod= "Junk::Stuff"; eval "require $mod; 1;" or die "$@"; $obj= $mod->foo("bar");

    This is more likely what you want.

      That eval/use is a bit over the top, although it'll work. I'll prefer this:
      BEGIN { if ($some_condition) { require Win32::SerialPort; import Win32::SerialPort qw(:ALL); } else { require Device::SerialPort; import Device::SerialPort qw(:ALL); } }
      There. A conditional "use".

      P.S. I just typed this earlier today on comp.lang.perl.tk. I wonder if this is the same person. {grin}

      -- Randal L. Schwartz, Perl hacker

        Good point. I was thinking of the general case when the module name is in a scalar. But I couldn't come up with a good example of that for the first example. Of course, you can try converting "::"s to the appropriate directory separators and adding on ".pm", put I think porting that to VMS would be some work (I'd probably pull in parts of MakeMaker).

        But for the example I came up with, your solution is superior.

Re: Stupid OO question
by lindex (Friar) on Aug 02, 2000 at 21:02 UTC
    Well I did a little reading (wow imaging that :)
    And I think I just need to get real close and personal with
    Inheratance's ( <-- how ever its spelled )
    maybe like (if reading a list of pm's from a db)
    while($sth->fetchrow_hashref) { push(@ISA,${$_}{name}); }
    or something to that effect :)



    lindex
    /****************************/ jason@gost.net, wh@ckz.org http://jason.gost.net /*****************************/