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

I would like to write a Singleton class. I noticed there is a a module called Class::Singleton on CPAN but I am not sure if I need that.

What's wrong with this code ?

package Sing; use strict; use warnings; my $obj; sub new { my ($class) = @_; $obj = bless {}, $class if not $obj; return $obj; } 1;

Replies are listed 'Best First'.
Re: Singleton
by merlyn (Sage) on May 18, 2005 at 15:47 UTC
    Well, you can't inherit from that. If someone calls the subclass, they get this method, and it plugs your singleton for the parent class. Ouch.

    A package is already a singleton. Just make all your methods be class methods, and return $class instead of trying to bless something.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

Re: How to create a singleton class ?
by diotalevi (Canon) on May 18, 2005 at 17:22 UTC
    I'd suggest you just read the source for Class::Singleton. It short. There are only ten-ish lines of actual code. The net effect is, you'll either write a replacement for Class::Singleton or you'll use the real one. The function is just that basic.
Re: Singleton
by Fletch (Bishop) on May 18, 2005 at 15:50 UTC

    I'd personally have said ... unless defined $obj but that's just me. Other than that it should work fine as a barebones singleton. Class::Singleton provides hooks for initialization of the instance by subclasses, but that's not much harder.

Re: How to create a singleton class ?
by brian_d_foy (Abbot) on May 18, 2005 at 17:06 UTC