Search code examples
perlsingleton

How can I implement a singleton class in perl?


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


Solution

  • 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;
    }