Reputation: 23
When I create 2 separate Perl object instances the second one is overwriting the data of the first one. I am new to OO Perl so I think I am missing something basic in how I am handling the $self variable inside the class. Why does the data of $ptr2 object overwrite the data of $ptr1 object? Its probably an easy 1 minute answer from Perl experts but I have been beating my head over this. My actual application is supposed to grab a bunch of data from different sources and run some data analysis, so what I have below is a simplified version to show the problem at hand.
I did check one other question related to the same topic below but it seems to be different from my problem.
Below is what I have in the class:
package TestClass;
sub new {
my ($object, $file) = @_;
my $class = ref($object) || $object;
my $self = { myfile => $file, };
bless($self, $class);
return($self);
}
# grabs key-val pairs from file
sub getFileData {
my($self) = @_;
open (FILE, "$self->{myfile}" ) or die "Cannot open\n";
while (my $curline = <FILE>) {
my @fields = split(/\s+/,$curline);
$self{$fields[0]} = $fields[1];
}
close FILE;
}
# prints key-val pairs to stdout
sub printFileData {
my($self) = @_;
foreach my $key (keys %self) {
print "$key -> $self{$key}\n";
}
}
1;
Below is how I am calling the class objects:
use TestClass;
my $ptr1 = TestClass->new("test1.txt");
my $ptr2 = TestClass->new("test2.txt");
$ptr1->getFileData();
print "This is correct for test1.txt\n";
$ptr1->printFileData();
$ptr2->getFileData();
print "This is wrong for test1.txt, test2.txt overwrote test1.txt\n";
$ptr1->printFileData();
$ptr2->printFileData();
test1.txt and test2.txt have single lines 'VAL1 1' and 'VAL1 2' respectively.
Output of the script looks as follows:
This is correct for test1.txt
VAL1 -> 1
This is wrong for test1.txt, test2.txt overwrote test1.txt
VAL1 -> 2
VAL1 -> 2
Upvotes: 2
Views: 152
Reputation: 1675
In TestClass.pm replace all instances of $self{$key}
with $self->{$key}
(lines 16 and 24), and %self
with %$self
(line 23).
Your output will look like this:
This is correct for test1.txt
myfile => test1.txt
VAL1 => 1
This is wrong for test1.txt, test2.txt overwrote test1.txt
myfile => test1.txt
VAL1 => 1
myfile => test2.txt
VAL1 => 2
On a side note, if you use strict;
Perl will catch these sorts of errors for you.
Upvotes: 6