Trying to get the hang of using OOP in Perl. My problem is that I’m setting a variable in the class, but the value is lost when I try and retrieve it. I’m sure the issue is glaring, but I need some extra eyes.
Constructor:
sub new
{
my ($class, $name) = @_;
my $self = {
_name => $name,
_times => []
};
bless ($self, $class);
return $self;
}
accessor/mutator method:
sub times {
my ($self) = shift;
if (@_) { @{$self->{_times}} = shift }
print "times size: " . @{$self->{_times}} . "\n";
return @{$self->{_times}};
}
call from the main program:
$js->addRun($duration, $curStartTime);
print "Times size: " . @{$js->times()} . "\n";
relevant code from addRun() subroutine:
sub addRun {
my ($self, $duration, $runDateTime) = @_;
if (!defined($duration) || !defined($runDateTime)) { return 0; }
push(@{$self->{_times}},$duration);
}
When I run this code, it enters the addRun subroutine and pushes the value to the _times variable. Then I print the value by calling the accessor/mutator. But the accessor/mutator has its own print command, so I can check the value before I return it.
The accessor prints the correct value, but when I print what was returned, it’s undefined. Is my syntax messed up somewhere? Am I just an idiot?
Thanks
The problem is in your times() subroutine you are returning an array, not an array reference.
Then in your main program you are trying to dereference the call to times() but you don’t need to.
So in your main program just call it as follows:-