Lexically Scoped Methods for a specific class (aiming at PDL).
In PDL, we have a lot of methods that only make sense for certain analyses, yet when we use a PDL module that defines a set of functions, the module almost always imports its functions into the PDL package. For example, it is rarely useful to apply a one-dimensional Fourier transform to an image, but if any of my code says
use PDL::FFT, I can suddenly do so anywhere else in my code.
The Perl world seems to be moving more and more towards lexically scoping a set of ideas or concepts. Lexically scoped variables was a first and huge step in this direction. We have recently seen (with Perl 5.18) the introduction of lexically scoped subroutines. We can then ask: does it make sense to lexically scope PDL functionality?
I don't know if the correct answer is "yes" or "no," but I hope that this working code example gives us some room to play with the idea. The basic idea is that Bar.pm implements a method for the Foo class, and it exposes that method to the Foo class only in the lexical scope(s) where it is used. The machinery necessary for this lexical scoping requires a lexical-method-mapping API for the Foo class, as well as the necessary code to find and invoke lexically scoped methods. The Bar.pm module then simply uses the API to add its methods.
Work in progress
I have been told that the autoloading code in Foo.pm may be overengineered. In particular, I was told that
AUTOLOAD() is only invoked after method resolution fails, so checking if the superclass can do the requested method is a waste of time.
It is somewhat annoying to have to write a custom
unimport() method for each class that will use this approach. This can be solved by writing a PDL::Exorter::Lexical, which could be used to perform the proper lexical handling using package globals defined in the
Bar (or similar) package.
How do I run this thing?
To run this, download Bar.pm, Foo.pm, and lexical-methods.pl into the same folder and execute the Perl script.