Greetings Monks! I seek your enlightenment. How do I make objects interact with each other? For instance, lets say I have one object attack another object? How do I change an objects internal data?
#!/usr/bin/perl
use strict;
use warnings;
use Peasant;
my $henry = Peasant->new(name => "Peasant1", hp => "15");
my $joe = Peasant->new(name => "Peasant2", hp => "15");
$joe->damage($henry->attack);
$henry->damage($joe->attack);
package Peasant;
use strict;
sub new {
my ($class, %arg) = @_;
my $objref = {
_name => $arg{name} || "unknown",
_hp => $arg{name} || "unknown"
};
bless $objref, $class;
return $objref;
}
sub damage {
print "$_[0] damage\n";
$_[0]->{_hp} - $_[0];
}
sub name { return $_[0]->{_name} }
sub attack {
my $int = int(rand(5));
print "$_[0]->{_name} attacks for $int.....\n";
return $int;
}
1;
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.