September 2012 Archives

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.

About Wolfgang Kinkeldei

user-pic I blog about Perl.