Simple Singleton in a few lines

The other day I was working on a library which needed to have a small list of dependencies and guaranteed to run on Perl versions 5.10 and above. In order to keep the dependencies minimal I decided to code a singleton() method like this:

sub instance {
    my $class = shift;
    state $self = $class->new(@_);

    return $self;

Just to get me right. This is not a complain to Moo*X::Singleton modules. The snippet above is very primitive, does not provide a separate initialization and has no way of clearing an instance. But sometimes this simplicity might do its job.


It's not really a singleton if other code can also call new. I'd call it a class with a default instance. If you want to prevent other code from calling new you could check caller(0) from within new and throw an error if it's not your instance method.

FWIW, the following is even more concise and works in older versions of Perl:

my $instance;
sub instance { $instance ||= shift->new(@_) }

Leave a comment

About Wolfgang Kinkeldei

user-pic I blog about Perl.