Fellow monks,

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 ...

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 error message returned at runtime by the line containing "# this doesn't" is:
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.
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.

Thank you for any light you can shed on this!


In reply to Problem using object references as hash keys by jlf

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.