Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement a singleton class in perl?

Tags:

singleton

perl

What's the best practice for implementing Singletons in Perl?

like image 776
planetp Avatar asked Feb 22 '10 10:02

planetp


1 Answers

You can use the Class::Singleton module.

A "Singleton" class can also be easily implemented using either my or state variable (the latter is available since Perl 5.10). But see the @Michael's comment below.

package MySingletonClass;
use strict;
use warnings;
use feature 'state';

sub new {
    my ($class) = @_;
    state $instance;

    if (! defined $instance) {
        $instance = bless {}, $class;
    }
    return $instance;
}
like image 142
Eugene Yarmash Avatar answered Oct 03 '22 09:10

Eugene Yarmash