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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Perl OO newbie advice - object interaction
by japhy (Canon) on Jun 21, 2006 at 11:28 UTC |