-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path12-1.pl
95 lines (75 loc) · 1.7 KB
/
12-1.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
use strict;
use warnings;
use Carp qw(croak carp);
{
package Animal;
sub factory {
ref (my $class = shift) and Carp::croak "class only.";
my $name = shift;
my $color = shift;
my $self = {
'name' => $name || "unnamed",
'color' => $color || "brown",
};
bless $self, $class;
}
sub name {
my $self = shift;
if (!ref $self) {
my $caller = (caller(0))[3];
Carp::croak "Called an instance method $caller from a class.";
}
if (@_) {
#setter
my $old = $self->{'name'};
$self->{'name'} = $_[0];
return $old;
}
else {
#getter
return $self->{'name'};
}
}
}
{
package Horse;
our @ISA = qw(Animal);
}
{
package RaceHorse;
our @ISA = qw(Horse);
sub factory {
ref (my $class = shift) and Carp::croak "class only.";
my $self = $class->SUPER::factory(@_);
$self->{'stats'} = {};
$self->{'stats'}{$_} = 0 foreach qw(wins places shows losses);
print "FACTORY: ", $self->{'name'}, "\n";
my $fn = _get_file_name($self);
print "FN: $fn\n";
dbmopen(%{$self->{'stats'}},$fn,0666);
$self;
}
sub won {shift->{'stats'}{'wins'}++;}
sub placed {shift->{'stats'}{'places'}++;}
sub showed {shift->{'stats'}{'shows'}++;}
sub lost {shift->{'stats'}{'losses'}++;}
sub standings {
my $self = shift;
join ", ", map {
"$self->{'stats'}{$_} $_"
} qw( wins places shows losses );
}
sub _get_file_name {
my $self = shift;
return "./" . $self->name . ".history3";
}
sub DESTROY {
my $self = shift;
dbmclose(%{$self->{'stats'}});
}
}
my $runner = RaceHorse->factory("Billy Bob");
my @fns = qw(won placed showed lost);
my $random_fn = $fns[int(rand(4)) + 0];
$runner->$random_fn;
print $runner->name, " has standings ", $runner->standings, ".\n";