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 callingnew
you could checkcaller(0)
from withinnew
and throw an error if it's not yourinstance
method.FWIW, the following is even more concise and works in older versions of Perl:
actually, I prevented others from calling new on my class but omitted this detail here, as it was more complicated than checking caller(0) because in my actual implementation I used ->new_with_options in a similar way MooseX::Getopt is working, so I had to check the call-stack a bit more.
admittedly your version is more concise and tolerant to older versions of perl. Thanks for the hint.