Enshu701.pl
use lib './';
use Product;
my $pd = new Product();
my $i1 = $pd->get(1);
print $i1->toString() . "\n";
my $i2 = $pd->get(3);
print $i2->toString() . "\n";
my $i3 = $pd->get(1);
print $i3->toString() . "\n";
Information.pm
package Information {
sub new {
my ($class, $n, $d, $p1, $p2) = @_;
my $this = { name => $n, # 製品名
district => $d, # 産地
retailPrice => $p1, # 小売価格
purchasePrice => $p2, # 買い付け価格
comment => () # コメント(複数持てる)
};
return bless $this, $class;
}
sub toString {
my ($this) = @_;
my $s = "製品名:" . $this->{name} . "、小売価格:" . $this->{retailPrice};
if (@{$this->{comment}} > 0) {
$s .= "、コメント:";
for(my $i = 0 ; $i < @{$this->{comment}} ; $i++) {
$s .= "[" . $this->{comment}[$i] . "]";
}
}
return $s;
}
sub setRetailPrice {
my ($this, $p) = @_;
$this->{retailPrice} = $p;
}
sub setComment {
my ($this, $c) = @_;
push @{$this->{comment}}, $c;
}
}
1;
Database.pm
package Database {
sub new {
my ($class) = @_;
print "(データベースへの接続)\n";
return bless {}, $class;
}
sub selectProduct {
my ($this, $id) = @_;
print "(データベースからの読み込み)\n";
my @rec = ();
push @rec, "製品名" . $id;
push @rec, "産地" . $id;
push @rec, "" . ($id * 200); # 小売価格
push @rec, "" . ($id * 100); # 買い付け価格
return @rec;
}
# その他いろいろできるメンバ関数
# :
# :
}
1;
Product.pm
use Database;
use Information;
package Product {
use base qw(Database);
sub new {
my ($class) = @_;
my $this = $class->SUPER::new();
return bless $this, $class;
}
sub get {
my ($this, $id) = @_;
my @s = $this->selectProduct($id);
my $info = new Information(@s[0], @s[1], @s[2], @s[3]);
return $info;
}
}
1;
Product.pm
use Database;
use Information;
package Product {
use base qw(Database);
sub new {
my ($class) = @_;
my $this = $class->SUPER::new();
$this->{list} = {};
return bless $this, $class;
}
sub get {
my ($this, $id) = @_;
my $info;
if (exists($this->{list}{$id})) {
$info = $this->{list}{$id};
}
else {
my @s = $this->selectProduct($id);
my $info = new Information(@s[0], @s[1], @s[2], @s[3]);
$this->{list}{$id} = $info;
}
return $info;
}
}
1;