http://qs321.pair.com?node_id=411068

beable has asked for the wisdom of the Perl Monks concerning the following question:

How do you determine if a user-defined function exists? For example:
sub myfunc { return "blah blah" . shift; } sub checker { # here I want to find out if myfunc() exists, but # without executing it. # myfunc() might be in a module somewhere. }

Replies are listed 'Best First'.
Re: How do you determine if a user-defined function exists?
by ikegami (Patriarch) on Nov 29, 2004 at 23:44 UTC

    You can check if it's in a specific package, but

    • I don't know anything that checks if a function exists in any package (so I coded up a solution below).
    • I don't know anything that checks if a function is in a module (and that's impossible to do correctly given Perl's dynamic nature).
    • I don't know anything that checks if a function is in any module on the machine (and that's impossible to do correctly given Perl's dynamic nature).

    In the current package:

    UNIVERSAL::can(__PACKAGE__, 'myfunc')

    In a specific package:

    UNIVERSAL::can($pkg, 'myfunc')

    In any package:

    sub check_for_func { my ($func_name) = @_; my @pkgs_with_func; my $helper; # Don't combine this line with the assignement. $helper = sub { my ($pkg_name) = @_; my $pkg = do { no strict 'refs'; \%{$pkg_name.'::'} }; push(@pkgs_with_func, $pkg_name) if $pkg->{$func_name} && *{$pkg->{$func_name}}{CODE}; my $pkg_name_ = ($pkg_name eq 'main' ? '' : $pkg_name.'::' ); /^(.*)::$/ && $1 ne 'main' && &$helper($pkg_name_.$1) foreach (keys(%$pkg)); }; &$helper('main'); return @pkgs_with_func; } print(join(', ', check_for_func('test')), $/);

      ikegami++, good reply. The only thing I'd do differently is use the class method syntax for calling UNIVERSAL::can. I think it looks nicer:

      __PACKAGE__->can('myfunc'); $pkg->can('myfunc');

        Not only does it look nicer (especially with CLASS), but it allows packages and modules to overload can() too.

Re: How do you determine if a user-defined function exists?
by bart (Canon) on Nov 30, 2004 at 01:13 UTC
    defined &myfunc
    This does not call the function.
Re: How do you determine if a user-defined function exists?
by ysth (Canon) on Nov 30, 2004 at 07:12 UTC
    defined &myfunc will tell if it is defined, but usually (especially for imports from modules) it is better to see if it is declared instead; exists &myfunc will do that. The difference is functions that have a forward declaration like sub myfunc; and are implemented via AUTOLOAD (e.g. AutoLoader/SelfLoader). exist &foo will be true for these functions, but defined &foo will not.