So, I was thinking about this (per object overrides of methods) on the train this morning. The 'traditional' way to specialize an object in perl is to generate a new class name for each specialized object, set its @ISA to the class of the object being specialized, and bless the object into the new class.
And it works. Sort of. The problem is that it can leak memory more and more classes get created and their instances get destroyed leaving entire symbol tables lying around orphaned. The naive approach is to shove a DESTROY method into the specialized class, but that's no good if you're specializing the object in order to add your own DESTROY behaviour.
So, wouldn't it be great if you could do this:
# Specialize takes a hash of method names and # subroutines sub specialize { my $self = shift; my %method = @_;In other words, one could create classes that are blessed with anonymous symbol tables. Because the symbol table is anonymous it will be garbage collected by the system when the specialized object goes out of scope.
my $syte = {} $syte->{ISA} = gensym; *{$syte->{ISA}} = [ ref($self) ];
foreach my $key (keys %method) { $syte->{$key} = gensym; *{$syte->{$key}} = $method{$key}; } bless $self, $syte; }
Re:Instances
pdcawley on 2002-03-22T22:57:47
Having taken a closer look at Class::Classless (nice work there btw), I'm sure that that approach could be made to work, but:
- AFAICT it'll only work for blessed hashes, and I'm not even sure it'd work that well with them.
- Even assuming you're happy with nothing but blessed hashes, I'm not entirely sure it'd be possible to write a UNIVERSAL::specialize that would allow you to lazily specialize any object you like.
- An anonymous symbol table approach would almost certainly be substantially faster.
Of course, Class::Classless has the enormous advantage of actually existing.
Which is definitely a big advantage.
I like anonymous symbol tables as an idea though. I'm sure there's lots more that could be done with them than just specialized objects. Blessed symbol tables anyone?