This drives me crazy !!!

F

Foo Bar

Singleton.pm:
=============
package Singleton;
my $instance = undef;
sub new
{
if (!defined $instance) {
$instance->{count} = 0;
bless($instance, 'Singleton');
}
return $instance;
}
1;

Obj.pm:
=======
package Obj;
use Singleton;
@Obj::ISA = qw(Singleton);
sub count {
my $self = shift;
return $self->{count}++;
}
1;

test.pl:
========
#!/usr/bin/perl -w
use Obj;
my $obj = new Obj;
print $obj->count, "\n";

Friggin' error:
===============
Can't locate object method "count" via package "Singleton" at test.pl line 60.

Even I tried to throw in Singleton as follow and it didn't help:
BEGIN
{
use Exporter ();
@Singleton::ISA = qw(Exporter);
}

Dang...I'm too tired to figure out what goes wrong!!!!
 
T

Tassilo v. Parseval

Also sprach Foo Bar:
Singleton.pm:
=============
package Singleton;
my $instance = undef;
sub new
{
if (!defined $instance) {
$instance->{count} = 0;
bless($instance, 'Singleton');

This will bless the object into the hard-coded class
'Singleton'.
}
return $instance;
}
1;

Obj.pm:
=======
package Obj;
use Singleton;
@Obj::ISA = qw(Singleton);
sub count {
my $self = shift;
return $self->{count}++;
}
1;

test.pl:
========
#!/usr/bin/perl -w
use Obj;
my $obj = new Obj;

Here you want to create an object that is an instance of the class Obj.
Obj inherits new() from Singleton which always blesses the created
object into 'Singleton'. However, you want it to bless into 'Obj'.

So change the inherited new():

sub new {
my $class = shift;
if (!defined $instance) {
$instance->{count} = 0;
return bless $instance => $class;
}
}

Tassilo
 
F

Foo Bar

Tassilo v. Parseval said:
This will bless the object into the hard-coded class
'Singleton'.

Arrrrggggg!!! Staying up late sure has its effect! Thanks, Tassilo.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,135
Latest member
VeronaShap
Top