saving keystrokes in sub export lists

rjbs on 2006-12-05T18:42:53

I use Sub::Exporter a good bit. It makes my life easier by letting me generate nice, simple mixins. I think I just had a good idea for typing even less.

Right now, to export routine, you might write this:

package Toolkit;
use Sub::Exporter -setup => {
  exports => [ 'routine' ],
};

If you write a subclass of your Toolkit module, and it defines its own routine, that's what will be exported, because Sub::Exporter uses the universal can method to find routine.

If you want the routine sub to be generated at import time, based on args to the import call, you'd write something more like this.

package Toolkit;
use Sub::Exporter -setup => {
  exports => [ routine =>  \&_gen_routine ],
};

Now when someone imports routine, it's generated by calling the _gen_routine sub, which is passed these args:

$class - the class on which import was called
$name  - the name of the routine being generated
$arg   - arguments passed to the generator in the import line
$col   - arguments passed to the whole importer in the import line

The problem is that since you've given the exporter a reference to a specific routine, you can't just replace the generator in a subclass. The way you'd do that, now, is like this:

package Toolkit;
use Sub::Exporter -setup => {
  exports => [ routine =>  sub { shift->_gen_routine(@_) } ],
};

Well, it works, but who wants to write that over and over? I could make a Sub::Exporter::Util for it, but that's a pain to type, too.

Just now, a vision of overload.pm popped into my head (blinding me briefly; fortunately, I was not crossing the road), and I realized that I could easily make this work:

package Toolkit;
use Sub::Exporter -setup => {
  exports => [ routine =>  \'_gen_routine' ],
};

Now I can easily write subclasses of routine factories! Time to go mix some stuff in.