richb has asked for the wisdom of the Perl Monks concerning the following question:
Second, the test code that references the Test package.package Test; sub new { my $class = shift; my $self = {}; bless $self, $class; return $self; } sub getValue { my $self = shift; $self{theValue}; } sub setValue { my $self = shift; my $value = shift; $self{theValue} = $value; }
use Test; my $test = new Test; print "test is " .$test ."\n"; print "test getValue after new is " .$test->getValue() ."\n"; $test->setValue(1); print "test getValue after setValue(1) is ". $test->getValue() ."\n"; print "\n"; my $test1 = new Test; print "test1 is " .$test1 ."\n"; print "test1 getValue after new is " .$test1->getValue() ."\n"; #print "test getValue after test1->new is ". $test->getValue() ."\n"; $test1->setValue(2); print "test1 getValue after setValue(2) is " .$test1->getValue() ."\n" +; print "test getValue after test1->setValue(2) is ". $test->getValue() +."\n";
I am surprised that test1 "steps on" test because the hash keys are different for test and test1. $test->setValue(1) sets the value to 1 for the test object, but after calling $test1->setValue(2), both test and test1 report 2 when getValue is called. So it seems I have a class variable here, one that holds the same value for all instances of the class. How do I get an instance variable, where each class instance maintains its own distinct value?test is Test=HASH(0x88fbc20) Use of uninitialized value in concatenation (.) or string at test.pl l +ine 9. #expected test getValue after new is test getValue after setValue(1) is 1 test1 is Test=HASH(0x88fbde8) #different than test test1 getValue after new is 1 #wow, test1 "inherited" the value set by + the test object test1 getValue after setValue(2) is 2 test getValue after test1->setValue(2) is 2 #and now test sees 2, inst +ead of 1
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Perl class - how to create instance variable instead of class variable
by Fletch (Bishop) on Aug 29, 2007 at 17:09 UTC | |
| |
|
Re: Perl class - how to create instance variable instead of class variable
by lyklev (Pilgrim) on Aug 29, 2007 at 20:30 UTC | |
|
Re: Perl class - how to create instance variable instead of class variable
by Anno (Deacon) on Aug 29, 2007 at 17:39 UTC | |
|
Re: Perl class - how to create instance variable instead of class variable
by TGI (Parson) on Aug 30, 2007 at 01:08 UTC | |
by Anonymous Monk on Dec 11, 2010 at 11:42 UTC | |
by TGI (Parson) on Dec 20, 2010 at 05:36 UTC |