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

Dear Monks,

I have this module which might have a sub called 'create'.
However, there is a chance it doesn't have this method. How can one tell a package (or object) has this method ??

Thanks in advance
Luca

Replies are listed 'Best First'.
Re: How to tell methods exist in a package
by tirwhan (Abbot) on Nov 20, 2005 at 10:31 UTC
    perldoc UNIVERSAL, take a look at the can method. Or (if you're writing a test), use the can_ok method from Test::More.

    Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -- Brian W. Kernighan
Re: How to tell methods exist in a package
by g0n (Priest) on Nov 20, 2005 at 11:44 UTC
    http://perldoc.perl.org/functions/exists.html

    use strict; use warnings; if (exists &FOO::bar) { print "bar exists in foo\n"; } package FOO; sub bar { }
    Update: tirwhan has raised an important distinction. This method will only tell you if the package contains a sub with that name. If the package inherits a sub with that name, it won't return true. So the choice depends on whether your logic requires 'package has subroutine named x' or 'package can do x'.

    --------------------------------------------------------------

    "If there is such a phenomenon as absolute evil, it consists in treating another human being as a thing."

    John Brunner, "The Shockwave Rider".

      This will however not show up inherited methods. Which can be the desired behaviour in certain cases of course.

      use strict; use warnings; if (exists &FOOBAZ::bar) { print "bar exists in foo\n"; } if (FOOBAZ->can("bar")) { print "FOOBAZ can do bar\n"; } package FOO; sub bar { } package FOOBAZ; use base("FOO");

      Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -- Brian W. Kernighan
        What if the package is; $val = "FOO" ;
        This doesn't work: if (exists &$val::mySub) {...}

        Thanks
        Luca
Re: How to tell methods exist in a package
by kulls (Hermit) on Nov 21, 2005 at 04:24 UTC
    hi,
    you can also read this module 'use AutoLoader', for How to handle these kind of error ('method not defined')error.
    more info : AutoLoader
    -kulls