Hello monks!
I need wisdom and sage advice about the Right Way ( or Ways ) to pull in modules at runtime. This is along the lines of
getting the name of the module in runtime and calling a function from that module, but in an OO context.
Consider my situation:
The goal is this -- I have many different types of data collections in different languages, including nontext data - I want to be able to select the appropriate parser from a config file so that I can benefit from polymorphism. I ask the parser for word lists, and I don't want to worry about what 'word list' means for that docment collection. For some it will mean splitting on white space, for others it will be sophisticated part-of-speech tagging - whatever.
I have a document collection object ( LSI::Collection ) whose constructor reads a config file to figure out which parser to use. This parser can come in many, many flavors, all of them subclasses of a common ancestor, which serves as the default if none is defined in the config file.
My problem is this - some of these parsers do a lot of setup in the class constructor, which makes for a long wait at startup. Also, I don't want to clutter my Collection class with a zillion 'use' or 'require' statements. Here is a solution that I've found to dynamically require modules as needed, but it my bones it feels like the wrong way to do it:
my $parser;
my $m = $params{'parse_method'}; # from the config file
# this is a hash of parser names to modules
my %flavors = (
'POS' => 'LSI::Parser::POS',
'Regexp' => 'LSI::Parser::POS::Regexp',
'JSTOR' => 'LSI::Parser::POS::JSTOR'
);
my $flavor = $flavors{ $m } || 'LSI::Parser'; # default
# This is what makes me uneasy...
eval "require $m" ;
$self->{'parser '} = ($m)->new();
Is there a better way to do this? What is a virtuous way to add error handling here? Humble thanks in advance.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.