Hello Monks,

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:

#!/usr/bin/perl -w use strict; require $ARGV[0]; my $sub = eval "\\&$ARGV[1]"; &$sub;
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.

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.