in reply to Perl OO newbie advice - object interaction

A number of bugs in there. First, you need to fix the code for initialising hit points in your constructor:

_hp => $arg{hp} || rand (10) + 2

These are objects. You get your blessed object as the first parameter when a sub is called against an object so:

sub damage { my ($self, $hits) = @_;

and you can use the object ref to acces the object data:

$self->{_hp} - $hits;

Taken all together your code ends up like:

use strict; use warnings; package Peasant; use strict; sub new { my ($class, %arg) = @_; my $objref = { _name => $arg{name} || "unknown", _hp => $arg{hp} || rand (10) + 2 }; bless $objref, $class; return $objref; } sub damage { my ($self, $hits) = @_; print "$hits damage\n"; $self->{_hp} - $hits; } sub name {return shift->{_name}; } sub attack { my $self = shift; my $int = int(rand(5)); print "$self->{_name} attacks for $int.....\n"; return $int; } 1; package main; my $henry = Peasant->new(name => "Henry", hp => "15"); my $joe = Peasant->new(name => "Joe", hp => "15"); $joe->damage($henry->attack ()); $henry->damage($joe->attack ());

which prints:

Henry attacks for 1..... 1 damage Joe attacks for 1..... 1 damage

DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: Perl OO newbie advice - object interaction
by japhy (Canon) on Jun 21, 2006 at 11:28 UTC
    I think you're forgetting that the damage() method has to actually alter the object's hit-points:
    sub damage { ... $self->{_hp} = $self->{_hp} - $hits; # or, more succinctly: # $self->{_hp} -= $hits; }

    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart