Problem with multiple instances of a module

  • Thread starter hoeeg (at) post4.tele.dk
  • Start date
H

hoeeg (at) post4.tele.dk

Hi, i thought i had this OO thing figured out, but apparantly not.

I have a module i want to make multiple instances of.
All goes well with the first instance until i create a second instance,
then the first instance seems to be overwritten.

I have made a small test module to demonstrate the problem
--------------------------------------------
# perl module Testobject.pm
package Testobject;

sub new
{
my $class=shift;
my $self={};
$self{'id'}=shift;
bless ($self, $class);
print "New $self{'id'} - Self: $self\n";
return $self;
}


sub showid
{
my $self=shift;
my $caller=shift;
print "ID: $self{'id'} - Caller: $caller - Self: $self\n";
}


sub DESTROY
{
print "Bye-bye $self{'id'}\n";
}

1;
--------------------------------------------


And a small test program
--------------------------------------------
#!/usr/bin/perl -w

use Testobject;

$inst_1=Testobject->new("Inst-1");
$inst_1->showid("Inst_1");

$inst_2=Testobject->new("Inst-2");
$inst_1->showid("Inst_1");
$inst_2->showid("Inst_2");

undef($inst_2);
$inst_1->showid("Inst_1");
--------------------------------------------


When i run the program it outputs:
--------------------------------------------
New Inst-1 - Self: Testobject=HASH(0x2850e0)
ID: Inst-1 - Caller: Inst_1 - Self: Testobject=HASH(0x2850e0)
New Inst-2 - Self: Testobject=HASH(0x2851a0)
ID: Inst-2 - Caller: Inst_1 - Self: Testobject=HASH(0x2850e0)
ID: Inst-2 - Caller: Inst_2 - Self: Testobject=HASH(0x2851a0)
Bye-bye Inst-2
ID: Inst-2 - Caller: Inst_1 - Self: Testobject=HASH(0x2850e0)
Bye-bye Inst-2
 
A

Alan D. Salewski

Hi, i thought i had this OO thing figured out, but apparantly not.

I have a module i want to make multiple instances of.
All goes well with the first instance until i create a second instance,
then the first instance seems to be overwritten.

I have made a small test module to demonstrate the problem
--------------------------------------------
# perl module Testobject.pm
package Testobject; *snip*

When instance 2 is created, instance 1 takes on the identity of instance 2.

What have i overlooked?
*snip*

Hi hoeeg,

If you add 'use strict;' after the above package line in
Testobject.pm, perl will give you the info you seek.

HTH,
-Al
 

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

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top