jlf has asked for the wisdom of the Perl Monks concerning the following question:
I've been working on my first sizable project using object oriented Perl. The project is a card game with Player objects that act independently according to their own particular strategy for the game. There is a Hand class that manages the mechanics of play and tells each Player object the game state and requests it to make decisions based on this state. I'm passing an array of references to Player objects to the Hand constructor like so:
#!/usr/bin/perl -w use strict; use Player; use Hand; #... my @pl; push @pl, Player->new(name => Alice, strategy => aggressive); push @pl, Player->new(name => Bob, strategy => conservative); my $hand = Hand->new( players, \@pl ); $hand->play();
And in Hand.pm ...
The error message returned at runtime by the line containing "# this doesn't" is:sub new { my ($class, %arg) = @_; # ... bless { # ... _players => $arg{players} , }, $class; } sub play { my ($self) = @_; my %player; $self->{_players}[0]->out(); # this works # out() is a member function that prints some info about the Playe +r # add key containg ref to 1st player to %player and # with value of a reference to a new anonymous hash $player{$self->{_players}[0]} = {}; foreach my $this_player (keys %player) { $this_player->out(); # this doesn't } }
The reason I'm trying to use Player references as keys in the %player hash is that I need to keep track of each player's state as the hand plays out.Can't locate object method "out" via package "Player=HASH(0x1012ac74)" + (perhaps you forgot to load "Player=HASH(0x1012ac74)"?) at Hand.pm l +ine 63.
Thank you for any light you can shed on this!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Problem using object references as hash keys
by sgifford (Prior) on Jun 08, 2004 at 21:31 UTC | |
by jlf (Scribe) on Jun 10, 2004 at 00:12 UTC | |
|
Re: Problem using object references as hash keys
by Joost (Canon) on Jun 08, 2004 at 22:00 UTC | |
by jlf (Scribe) on Jun 10, 2004 at 00:15 UTC | |
|
Re: Problem using object references as hash keys
by eric256 (Parson) on Jun 09, 2004 at 03:05 UTC |