in reply to Inheritance and Container Classes and use/require

Hrmmm ... run-time compilation. *grins*

My favorite answer would be to encapsulate this into some sort of Factory, pass the factory the value, and have it create the instance of the correct class.

Of course, this is just punting the answer off to some factory class. How do you do it in the factory??

if ($value eq 'A') { eval "use Blah::First"; } elsif ($value eq 'B') { eval "use Blah::Second"; } else { eval "use Blah::Default"; }
Another, more extensible, possibility would be to do something like:
my $basedir = "/some/base/dir/for/perl/Blah"; require "$basedir/$value"; # or --- eval "use Blah::$value";
Now, require doesn't do an import() the way use does. Thus, if you have an import() anywhere in your hierarchy (typically if you use Exporter), then you have to make that function call yourself, maybe like "Blah::$value"->import(). That should work, but it is untested.

I would recommend the first alternative, unless you feel really wild and free. The second is a little less secure and you have less control over it.

Update: Changed to use eval, as per merlyn's comment.

------
We are the carpenters and bricklayers of the Information Age.

Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

Replies are listed 'Best First'.
Re: Re: Inheritance and Container Classes and use/require
by merlyn (Sage) on Jan 03, 2002 at 03:00 UTC
    That's not a conditional "use". Those "use" are all executed at compile time, and you've ended up with an if/elsif ladder that does nothing at runtime!

    -- Randal L. Schwartz, Perl hacker