sub whereami {
my $self = shift;
$self->{parent}->locate($self);
}
# in Parent
sub locate {
my $self = shift;
my $child = shift;
foreach my $x (0 .. $xmax) {
foreach my $y (0 .. $ymax) {
return ($x, $y) if $self->{children}[$x][$y] eq $child;
}
}
}
So that is how to do it - use the reference as a string. But do you want to do that?
TMTOWTDI. You could also store x and y information in the child objects. The parent could have a simple array of kids and grep through them for the right X and Y. Or you could pass the x and y on child creation and store the info in two places. Make sure that if you change that info, you change it in both places - use a single subroutine for changing x and y. Again, the subroutine could either be in the Parent class or the Child class, but it will operate on both objects.
A method is just a subroutine with an extra argument.
sub foobar {
my $foo = shift;
my $bar = shift;
# do stuff
}
is no different from
sub foobar {
my $bar = shift;
my $foo = shift;
# do stuff
}
as a subroutine. So in that sense, where you put your info is not that relevant. (Of course, inheritance is different. But that may not be an issue for you.)
So how do you choose? Well: do objects need to know the x and y of other objects? If so, that info needs to be publicly accessible in the Parent, using the locate method above. If objects only need to know where they are themselves, keep info in the Child.
Also, it looks to me as if x and y refer to co-ordinates. If so, do you really want a 2d array? This will make it easy to find columns:
@{ $self->{children}[$col] };
but awkward to find rows:
grep {$_->[$row]} @{$self->{children}}; # I think!
There is probably a solution on CPAN for grids... maybe Meta::Geo::Pos2d ? if not, there is certainly a full featured Array class that will make this stuff easier.
dave hj~ |