[OT] best way to determine existence of a function in a package

Nicholas Clark nick at ccl4.org
Mon Nov 19 10:50:02 GMT 2007


On Mon, Nov 19, 2007 at 10:33:49AM +0000, Jonathan Stowe wrote:
> On Mon, 2007-11-19 at 09:53 +0000, Dirk Koopman wrote:
> > The problem:
> > 
> > A user may include a local version of a package which may include one or 
> >   more local versions of a static function (there are no references, 
> > blessed or otherwise to ->can() on).
> > 
> > I want to detect whether or not that function is explicitly defined.
> > 
> > if (defined *Local::function) {
> >     ...
> >     ...
> > }
> > 
> > except that expression always returns true, which is rather a nuisance.
> 
> You cant to examine the CODE slot of the typeglob:
> 
> if (defined *Local::function{CODE} )
> {
>    # ....
> }
> 
> This may not work on ye ancieunte perls, but I can't remember when it
> was introduced.

You also can used exists and defined to see whether a subroutine
respectively has been declared and defined:

$ perl -le 'print exists &Pie; print defined &Pie'


$ perl -le 'sub Pie; print exists &Pie; print defined &Pie'
1

$ perl -le 'sub Pie {} print exists &Pie; print defined &Pie'
1
1


I'm not sure when that use of exists became legal. I think that defined has
been there for a lot longer

(Actually making tasty Pie filling is left as an exercise to the reader)

Nicholas Clark


More information about the london.pm mailing list