{ my $c = wrapper->instance; my $d = wrapper->instance; die "Mismatch" if $c != $d; } # wrapper->instance expires { my $e = wrapper->instance; { my $f = wrapper->instance; die "Mismatch" if $e != $f; } } # wrapper->instance expires package wrapper; BEGIN { our @ISA = ('Class::WeakSingleton') } sub ::DEBUG { 1 } my $count = 0; sub _new_instance { print "_new_instance()\n" if ::DEBUG; bless { (++$count) x 2 }, shift; } package Class::WeakSingleton; use Scalar::Util (); sub instance { my $class = shift; # get a reference to the _instance variable in the $class package no strict 'refs'; my $instance = "${class}::_instance"; return $$instance if defined $$instance; my $new_instance = $class->_new_instance(@_); $$instance = $new_instance; Scalar::Util::weaken( $$instance ); return $new_instance; }