I'm interested in some thoughts and comments on some code I recently developed to allow for automatic vivification of objects. If this looks reasonable, I would like to submit a module to CPAN.
The basic idea is that instead of creating an instance of a class, you would create an instance of the autovivifying class that calls an initialization function the first time it needs to and from then on you would have an object of the desired class.
Here's the code:
#!/usr/bin/perl use strict; use warnings; package AutoVivify; use vars qw/$AUTOLOAD/; sub new($$) { my ($class, $initializer) = @_; die "Initializer must be a code reference." unless (ref($initi +alizer) eq 'CODE'); my $self = {initializer => $initializer}; bless($self, $class); return $self; } sub AUTOLOAD { $_[0] = &{$_[0]->{initializer}}(); $AUTOLOAD =~ s/.*:://; eval "\$_[0]->$AUTOLOAD(\@_)"; } sub DESTROY { } 1;
Here's an example of usage:
#!/usr/bin/perl use strict; use warnings; package foo::bar; sub new() { return bless({}, shift); } sub aaa() { my $self = shift; warn "aaa"; $self->{foo} = "bar"; } sub bbb($$) { my $self = shift; warn shift; warn $self->{foo}; } package main; use AutoVivify; my $x = AutoVivify->new(sub {return foo::bar->new()}); $x->aaa(); #$x is now an object of type foo::bar $x->bbb(2);
One possible usage for something like this is for classes that have expensive initialization for an object. This defers initialization until absolutely needed without requiring the class to support deferred initialization.
Any suggestions for module names are appreciated as well (AutoVivify, Class::AutoVivify, etc.).
In reply to Automatic vivification of an object by bounsy
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |