in reply to how to find a subroutine exists or not

Update: Ah. This works, but only sort of. See diotalevi's response below, as well as the other posts in the thread.

This should work:

if (my $coderef = __PACKAGE__->can("test")) { $coderef->(); }

Update: it might be worth pointing out that this is equivalent:

if (__PACKAGE__->can("test")) { test(); }

And if you're in the main package, this is as well:

if (main->can("test")) { test(); }

Replies are listed 'Best First'.
Re^2: how to find a subroutine exists or not
by diotalevi (Canon) on Apr 20, 2006 at 15:38 UTC

    This works, sort of. It also brings in @ISA and any overloaded ->can(...) methods so you might find that __PACKAGE__->can( 'test' ) is true even if the current package doesn't have a &test function. You should have said defined &test which is the documented and backwards compatible way to test for this.

    ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

Re^2: how to find a subroutine exists or not
by mrpeabody (Friar) on Apr 20, 2006 at 16:11 UTC
    I think __PACKAGE__ should be mentioned in perlvar. I understand that it is not a "variable", strictly speaking, but it is a symbol with special meaning, and perlvar seems the obvious place to start looking for documentation.

    Perhaps just a mention of the name and pointer to perldata, so a quick grep can catch it.

      It's not a symbol, it's a special literal that's documented in perldata. That said, a mention of it in perlvar probably makes sense, too.

      -xdg

      Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.