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

Dear monks,
I need to check if a specific subroutine in a module exists. If it exists, I'll call it on the next line, so I could call it directly if this makes the test easier.
This project isn't using OO style and too many files would need to be converted, so this is no option.
I thought of something like
$Result = eval { A::B::$ModName::Sub($X); };
but I think a better solution would be testing if the sub exists before calling it. Is this possible?

Replies are listed 'Best First'.
Re: Check for sub / don't fail on non-existent sub
by SFLEX (Chaplain) on Aug 29, 2009 at 10:39 UTC
    I use this:
    my $sub_x = 'Some::Sub'; my $Result = 'Bad'; if (exists &{$sub_x} && (ref $sub_x eq 'CODE' || ref $sub_x eq '')) { $Result = 'Good'; } print $Result . "\n"

    What did the Pro-Perl programmer say to the Perl noob?
    You owe me some hair.
      Simpler:
      my $sub_x = 'Some::Sub'; if (defined(&$sub_x)) { print("It's there\n"); } else { print("It's not there\n"); }
        Wow, I expected that defined() would be applyed to the result of $sub_x, but a test showed that it doesn't.
        Thank you all!
Re: Check for sub / don't fail on non-existent sub
by Anonymous Monk on Aug 29, 2009 at 08:05 UTC
    use UNIVERSAL 'can'; my $sub = can "A::B::$ModName", "Sub"; if( $sub ){ $sub->($X); } my $res ; if( eval { $res= "A::B::$ModName::Sub"->($X); 1 } ){ return $res; }