I'm looking for a way to verify if a subroutine reference is valid. For example (when run with use strict, of course), my $sub = \&non_existent_sub; compiles fine, even if non_existent_sub was never declared. Worse still, $sub actually contains a CODE reference (to what? I'm not sure). It's only when I try to execute the sub (&$sub()) that perl fails, complaining of an undefined subroutine.
Is there any way to analyze $sub to determine that it points to an invalid subroutine? Apart from trying to execute it, of course. I've read Can I Force perl to Check Subroutine References at Compile Time?, but it didn't really answer my question, or if it did, then I missed it.
The reason I ask is that I'm trying to re-invent the user-supplied-code-execution wheel. I'm playing with an idea that's best captured in the following snippet:
The script's first argument is a file containing perl subroutine declarations, and the second argument is the name of the subroutine to call. My hope (correct me if I'm wrong) is that the require will catch user code errors early on, and resolving it to an actual subroutine reference simplifies calling the user code.#!/usr/bin/perl -w use strict; require $ARGV[0]; my $sub = eval "\\&$ARGV[1]"; &$sub;
Of course, my real application is much more convoluted. The supplied functions are used as callbacks in the program, so the callback link has to be declared early in the program (this is when I want to check user input) even if the function might only get called much much later, potentially not even in the same execution run.
Of course, I'm also open to criticism if this is all a horrible idea.
In reply to How do I test the validity of a CODE reference? by pilap
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |