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

In reply to Re: Perl OO newbie advice - object interaction by GrandFather
in thread Perl OO newbie advice - object interaction by yoda54

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.