in reply to Module vs Singleton
Singletons are easier than you might suppose to do in Perl ... but first, you’re going to have to “un-learn” some of your C++.
Perl objects live in packages. Yet, there is nothing special about them, except that they contain a subroutine which by convention is named new, and which contains something along the order of the following:
my $class = shift;
my $self = {};
bless $self, $class;
return $self;
Now, what this code is doing is to instantiate a hashref and then to bless it, which tells Perl that this hash (it could be some other kind of data-structure) is to behave like an object. Then, the subroutine returns that hashref. Since the hashref is being returned, it isn’t going out of scope so it isn’t destroyed by the garbage-collector.
So, how would you create a singleton? Through the use of a package variable. Like this:
my $singleton = undef; sub new { my $class = shift; unless (defined($singleton)) { $singleton = {}; bless $singleton, $class; } return $singleton; }
Now, only the first call to new will initiate a new object. Every successive call will simply return the same one.
When you are coming from a highly-strictured language like C++, working with Perl can sometimes feel like barnstorming. “Now that’s flying...!”
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Module vs Singleton
by Anonymous Monk on Jul 16, 2011 at 04:12 UTC | |
by Khen1950fx (Canon) on Jul 16, 2011 at 06:43 UTC | |
by locked_user sundialsvc4 (Abbot) on Jul 16, 2011 at 12:03 UTC | |
by Anonymous Monk on Jul 16, 2011 at 18:11 UTC |