#!/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);