Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

For sake of simplicity of an example, imagine basketball. Each player has statistics stored for them. Shots taken, shots made, points, rebounds, etc. I can handle objects that do that fine. The problem is when I want to group them by team, but still keep OO-ness (and not use an array of objects in my program). Maybe I'm missing something simple.. What would be the best way to group the basketball players by team? How would I retrieve stats for say, "Michael Jordan," including the team he is on/grouped in? What if someone refers to him by number and I want to get his name from that? Thanks

Replies are listed 'Best First'.
Re: The Grouping of Objects
by dws (Chancellor) on May 06, 2001 at 02:19 UTC
    Create a Team object, which holds references to each Player object that's a member of the team. Arrange for each Player to hold a reference to it's Team.

    I assume player lookup by numer is done within the context of a team. You could do it like this:

    $player = { grep $_->number() eq $n) $team->players(); print "Player $n is ", $player->name(), "\n" if $player;
      Your Smalltalk background is showing...

      Perl uses reference counting, not true garbage collection. That means that the above, which creates circular references, will create memory leaks. Therefore you should only have the reference go one way.

      What I would do is have Team be a class, and then have creating a player, and trading players, be methods of the Team object. The Player object would hold the name of the Team, but no direct reference to it.

      I think that does a good job of reflecting your likely usage pattern without creating memory leaks...

      UPDATE
      Alternate answer. With 5.6 use Devel::WeakRef.

Re: The Grouping of Objects
by princepawn (Parson) on May 08, 2001 at 00:46 UTC
    I would suggest you take a look at Data::DRef. This is a great, yet hardly-known about module.

    I will have to write up a review of it when I have sometime.