Hi,
This time I started to work on some project which, after some investigation, showed to be proper to be solved with object oriented programming. As it's new topic for me in Perl, shortly after some tests I hit on some problems. it's moreless about nesting the classes.
Before I come to the code, I'd like to present you waht kind of structures I'd like to be able to operate:
$mytest = new Test();
$mytest->name('BABA');
$mytest->condition('TYPE1')->value('whatever');
$mytest->special->do_something;
$mytest->special->condition('TYPE2')->value('other');
So, I thought, I will create one class for Test, which will have simply one properity of name, and another one will inherit from another construct (condition).
First I tried the following:
package Test;
@ISA = ("Condition");
#constructor
sub new
{
my ($class) = @_;
my $self =
{
_name => undef,
_condition => undef,
};
bless $self,$class;
return $self;
};
#accessors
sub condition
{
my ($self,$condition) = @_;
$self->{_condition} = new Condition() if defined($condition);
return $self->{_condition};
};
sub name
{
my ($self,$name) = @_;
$self->{_name} = $name if defined($name);
return $self->{_name};
};
package Condition;
#constructor
sub new
{
my ($class) = @_;
my $self =
{
_value => undef,
_list => undef,
};
bless $self,$class;
return $self;
};
sub value
{
my ($self,$value) = @_;
$self->{_value} = $value if defined($value);
return $self->{_value};
};
sub list
{
my $self = shift;
my @list = @_;
$self->{_list} = {@list} if defined(@list);
return @$self->{_list};
};
But than it says to me, it can't find the Test::Condition. So, I splitted it into two modules, and used "use Condition" at the beginning of Test module. This seems to solve the problem, but it's not the best what I'd like to have. Finally I do not want to create separate file for each single class.
Second problem is the following part:
sub condition
{
my ($self,$condition) = @_;
$self->{_condition} = new Condition() if defined($condition);
return $self->{_condition};
};
When I define the condition for $mytest:
$mytest->condition('ONE')->value('2 hours');
everything is fine. But when I try to get the value of it:
print $mytest->condition('ONE')->value;
It will return nothing, which is clear, because the constructor is called. My problem is now, how to check if the condition('ONE') exists, and return value (or whatever). Constructor should be called only if 'ONE' does not exists.