How to detect if a function / method exist without using AUTOLOAD

Here a little trick (thanks to SUKRIA) , to check if a function exist :

#check if key is a function
sub is_a_function {
    my ($function) = @_;
    no strict 'refs';
    no warnings 'redefine', 'prototype';
    return defined *{$function}{CODE};
}

#a more simple way
sub is_a_function {
    my ($function) = @_;
    return defined &$function;
}

So in your code :

if (is_a_function($myfunction) {
    $myfunction->(@params);
} else {
    croak "Unknown function $myfunction";
}

If you have a module you can use this way, with "can":

if ($self->can($method) {
    $self->$method(@params);
} else {
    croak "Unknown method $method";
}

Having fun with Perl!

Short URL

Comments