How can I determine if a Perl function exists at runtime?

Greg Hewgill picture Greg Hewgill · Jan 11, 2009 · Viewed 19.3k times · Source

I'm working on a test framework in Perl. As part of the tests, I may need to add precondition or postcondition checks for any given test, but not necessarily for all of them. What I've got so far is something like:

eval "&verify_precondition_TEST$n";
print $@ if $@;

Unfortunately, this outputs "Undefined subroutine &verify_precondition_TEST1 called at ..." if the function does not exist.

How can I determine ahead of time whether the function exists, before trying to call it?

Answer

jrockway picture jrockway · Jan 11, 2009
Package::Name->can('function')

or

*Package::Name::function{CODE}

# or no strict; *{ "Package::Name::$function" }{CODE}

or just live with the exception. If you call the function in an eval and $@ is set, then you can't call the function.

Finally, it sounds like you may want Test::Class instead of writing this yourself.

Edit: defined &function_name (or the no strict; defined &{ $function_name } variant), as mentioned in the other answers, looks to be the best way. UNIVERSAL::can is best for something you're going to call as a method (stylistically), and why bother messing around with the symbol table when Perl gives you syntax to do what you want.

Learning++ :)