This is a question from object oriented Perl. I am supposed to design a module:
1)Store the values
2)Calculate the Total, Mean, Count.
I am supposed to find a code which relates method overriding or polymorphism or inheritance in Object Oriented Perl.
My code is like this:
package Stats;
use strict;
use warnings;
sub new {
my $class = @_;
my $self = {};
bless $self, $class;
$self->clear();
return $self;
}
sub clear {
my $self = $_[0];
$self->{'numlist'} = undef;
$self->{'x_sum'} = 0;
$self->{'x2_sum'} = 0;
}
sub addValue {
my $self = $_[0];
my $num = $_[1];
if (defined $num) {
push @{$self->{'numlist'}}, $num;
$self->{'x_sum'} += $num;
$self->{'x2_sum'} += $num**2;
}
}
sub getTotal {
my $self = $_[0];
return $self->{'x_sum'};
}
sub getMean {
my $self = $_[0];
my @numlist = @{$self->{'numlist'}};
if (!@numlist) { return 0; }
return $self->getTotal()/@numlist;
}
sub getValueList {
my $self = $_[0];
return @{$self->{'numlist'}};
}
1;
sub results {
my $obj = new Stats(13,4,56,43,33);
print "Number of values: ", scalar($obj->getValueList()), "\n";
print "Total: ", $obj->getTotal(), "\n";
print "Mean: ", $obj->getMean(), "\n";
}
Where am I going wrong?
Ok. The object constructor syntax you are using is a bit akward, I’d prefer
In Perl,
newis not an ordinary keyword, but a simple sub, and should be used as such. TheFoo->sub(@args)syntax is exactly equivalent toFoo::sub('Foo', @args), and thus takes care of passing the correct class name and calling the correctnewsub.Then, you should use the numbers you are passing to your
Statsconstructor. This constructor should do the trick:I stuff all arguments of the constructor into the
@argsarray and then loop over them and add these values to our stats object.Also, do not forget to actually call
results()to execute your test. It will print: