vippagunta has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I have a Utility package which reads a couple of config files and does some other things like initializing log4perl etc. Other parts of my program(i.e. my other packages) need access to the contents of the config file and I don't want to pass the reference to my Utility package to other packages. So, I am thinking I need a Singleton. Is this the right approach?

Thanks,
Srini.

Replies are listed 'Best First'.
Re: Singleton question
by dHarry (Abbot) on Nov 17, 2009 at 07:28 UTC

    A logging service is a classic example of a Singleton. What confuses me is the "utility package". Maybe a Toolbox Singleton is a better way. See Use your singletons wisely for an interesting discussion on the topic. (Beware that these are java examples.)

    Cheers,

    Harry

Re: Singleton question
by pajout (Curate) on Nov 17, 2009 at 13:59 UTC
    Yes, in my opinion. For instance (just motivation code...):

    package My::Utils; my %instance; sub read_conf { #fills %instance } sub value { my ($name, $new_val) = @_; if (2 == @_) { #new value passed $instance{$name} = $new_val; } return $instance{$name}; } package My::Something use My::Utils; print My::Utils::value("something_configured");
    but I prefer to really create instance of the object, and then just call $utils_instance->value("something"). Of course, it needs a little different My::Utils.