Keep It Simple, Stupid | |
PerlMonks |
RFC: Lexcically scoped methods, a toy exampleby dcmertens (Scribe) |
on Jun 11, 2013 at 21:25 UTC ( [id://1038345]=perlmeditation: print w/replies, xml ) | Need Help?? |
PDL is a very general datatype. To one person, a 2D piddle may represent a collection of samples from a song while to another person a 2D piddle may represent an image. However, when you say use PDL::Image2D, various methods get installed into the PDL package, for all piddles to use. This naturally leads to the careful selection of long-winded names in a defensive approach to not getting your toes stepped on (or not stepping on somebody else's toes). It occurred to me a few days ago that we could manage this with lexically scoped methods. I don't mean lexically scoped subroutines (i.e. Lexical::Sub) because I really like PDL's method-chaining and want to keep that. Nor do I mean lexically scoped methods that get called on ALL objects, regardless of type (i.e. Method::Lexical) because I only want to (ultimately) modify the PDL method resolution. To achieve this, I wrote a simplistic but functional AUTOLOAD method that examines the hint hash to find mappings from method names to functions in other packages. Then, I wrote a pragma that modified the hints hash, adding a mapping. After a bit of confusion and fiddling, I finally got it to work. Here is an example to illustrate:
Outside of the lexical scope where I say "use Bar", calling the bar method on the Foo object issues an exception. Installing the mapping is quite simple:
Writing the class for which this works was a little trickier:
I've created a gist with this code example on github if anybody would like to play with it. I know that getting AUTOLOAD to work correctly is tricky, at best, but I also know that PDL doesn't get much in the way of complicated class dependencies underneath it, and I think it is possible to get this to work well enough that PDL might be able to use this sort of thing. Thoughts?
Back to
Meditations
|
|