sree.nivas has asked for the wisdom of the Perl Monks concerning the following question:
Hi, I have written small perl module and one script. In the constructor of the package, I am using one initializer method. The problem, I'm facing is: When, I create two different objects on the package, latest object's initialize methond is overwritting variables of previously created object. I dont have much knowledge on Perl. Unable to determine the cause. Requesting for some help. I am providing the code( of package and script and program output) below. thank you.
#######################################3 package MyPackage; use Data::Dumper; sub new { my $ip_addr = shift(); my $self = { "DEVICE_IP" =>$ip_addr }; bless $self, 'MyPackage'; $self->my_init(); return $self; } my $self_ip = undef; my $partner_ip = undef; my $WS_1 = undef; my $WS_2 = undef; #---------------------- sub my_init{ my $this = shift; ($WS_1, $WS_2 ) = ('10.199.35.11' , '10.199.35.12'); if($this->{DEVICE_IP} eq $WS_1) { $partner_ip = $WS_2; } else{ $partner_ip = $WS_1; } $self_ip = $this->{DEVICE_IP}; return $this; } #----------------- sub my_method{ my $this = shift; print "\n Local IP = $self_ip , Partner IP = $partner_ip \n"; return 1; } 1; __END__ ###################################3 #My script is as below: use MyPackage; my $local_ip= '10.199.35.11'; my $remote_ip = '10.199.35.12' ; my $objLocal = MyPackage::new($local_ip); my $ret = $objLocal->my_method(); my $objRemote = MyPackage::new($remote_ip); my $ret = $objLocal->my_method(); #####################################
# output observed is: Local IP = 10.199.35.11 , Partner IP = 10.199.35.12 Local IP = 10.199.35.12 , Partner IP = 10.199.35.11 Because, I am calling the same old object again, I am expecting the ou +tput to be: Local IP = 10.199.35.11 , Partner IP = 10.199.35.12 Local IP = 10.199.35.11 , Partner IP = 10.199.35.12
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: initializer method called from object constructor, overwriting the another object's variables
by Old_Gray_Bear (Bishop) on Oct 08, 2010 at 16:16 UTC | |
|
Re: initializer method called from object constructor, overwriting the another object's variables
by choroba (Cardinal) on Oct 08, 2010 at 15:42 UTC |