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') =~ 
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

About ugexe

user-pic Code requires [some order of magnitude] higher cleverness to read than to write, so if you are writing code at maximum cleverness, then you have already excluded yourself from being clever enough to understand it.