in reply to How do I test the validity of a CODE reference?

Seems you can also derive the answer by looking at the value of the CvOUTSIDE pointer attached to $sub. I think this will show up as the OUTSIDE value when you do a Devel::Peek::Dump($sub), but to access that value in a useful way from within a program you'll probably need XS/Inline::C:
use warnings; use Inline C => Config => BUILD_NOISY => 1; use Inline C => <<'EOC'; SV * validate(CV * coderef) { if(CvOUTSIDE(coderef)) return newSVuv(1); return newSVuv(0); } EOC $cref1 = \&existent; $cref2 = \&non_existent; $foo = 'hello world'; print "\$cref1: ", validate($cref1), "\n"; print "\$cref2: ", validate($cref2), "\n"; print "\$foo: ", validate($foo), "\n"; # Fatal Error sub existent{}
(I've not tested this approach beyond the extent provided by the above script.)

Cheers,
Rob

Replies are listed 'Best First'.
Re^2: How do I test the validity of a CODE reference?
by ikegami (Patriarch) on Aug 08, 2008 at 02:24 UTC
    defined (which already provides this functionality) and sub calls use CvROOT(sv) || CvXSUB(sv).

    Update: Only mentioned defined initially.

      defined (which already provides this functionality)...

      Yes, defined(&$sub) works fine, but the functionality seems different to me. My approach looks at the variable itself, whereas defined appears to be looking at the subroutine referenced by the variable.

      Anyway .... my point is very moot .... at best :-)

      Cheers,
      Rob
        Looks like they both operate on the same thing (the CV*) to me. (If not, please explain, since I'm not very familiar with this stuff.) So the question is why does Perl and your function use different tests to determine the same thing?
        #define CvROOT(sv) ((XPVCV*)SvANY(sv))->xcv_root_u.xcv_root #define CvXSUB(sv) ((XPVCV*)SvANY(sv))->xcv_root_u.xcv_xsub #define CvOUTSIDE(sv) ((XPVCV*)SvANY(sv))->xcv_outside