dstar has asked for the wisdom of the Perl Monks concerning the following question:

I'm using Class::Std for the first time, and I'm rather enjoying it, but one thing has me stumped. How do I make a singleton class using Class::Std? Googling brings up the possibility of using Memoize, but an abortive attempt reveals that Memoize and Class::Std do not play well together (or at least that I don't know how to get them to). Anyone care to enlighten me? EDIT: Apparently Memoize works just fine; it was a stupid-programmer-error. *sigh*

Replies are listed 'Best First'.
Re: Class::Std singletons
by xdg (Monsignor) on Mar 18, 2006 at 03:41 UTC

    One option is to consider an alternative inside-out system like Class::InsideOut that does not force a constructor/initialization approach on you.

    package My::Singleton; use Class::InsideOut qw( public register id ); public name => my %name; public rank => my %rank; my $self; sub new { $self ||= register( bless \(my $s), shift ); }

    Note: Class::InsideOut doesn't yet support Storable singletons, but it is on the Todo list for the next couple releases.

    -xdg

    Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Re: Class::Std singletons
by Herkum (Parson) on Mar 18, 2006 at 12:58 UTC

    If you want to use a singleton class with Class::Std then just don't the :ATTR hashes variables. The :ATTR is what makes the variables unique for each object. Get rid of this and then all of your variables will be shared by all the objects.

    To the program the objects will still look different but there will only be one set of values.

      That would work, I guess, but it's not a true singleton. Defining a class method to do it, ala:
      sub get_manager { $manager = AAPA::Manager->new(); $manager->set_galaxy(AAPA::Galaxy->new()); return $manager; }
      Doesn't work -- "Can't locate object method "get_manager" via package "AAPA::Manager" at ../AAPA/Ship.pm line 25." Fair enough, since get_manager's supposed to be a _class_ method. I just can't figure out how to tell Class::Std that...