Assigning a user defined function at runtime
I recently wrote my first XS module, and found myself wanting to dynamically load it in the parent module if possible. The next problem was what if the user wants to change back to the pure Perl version? And then, what if the user wants to use Other::Module's similar_function?
sub _set_backend {
my $be = shift;
my $module = $be;
$module =~ s/^(.*)::.*?$/$1/g;
# Does the module exist?
eval "require $module";
unless($@) {
# Does the module have such a function?
eval "defined &$be";
unless($@) {
# Does it return a number if we give it 2 strings?
eval "die unless(&$be('four','fuor') =~
/[-+]?[0-9]*\.?[0-9]+/)";
unless($@) {
# We welcome our new edistance overlord
*edistance = \&$be;
}
}
}
}
Of coarse we really only need the last eval, but this way we can return an appropriate error code if we want.
Leave a comment