in reply to Stupid OO question

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.

Replies are listed 'Best First'.
RE: Re: Stupid OO question
by merlyn (Sage) on Aug 03, 2000 at 03:02 UTC
    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.