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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.