package Fruit;
# コンストラクタ
sub new{
my $this = shift;
my ( $name, $value, $quantity ) = @_ ;
print "There are some $name"."s.\n\n" ;
my $fruit = {"Name" => $name,
"Value" => $value,
"Quantity" => $quantity } ;
bless $fruit, $this;
return $fruit ;
}
# デストラクタ
sub DESTROY{
my $this = shift;
print "$this->{Quantity} $this->{Name}s are disposed.\n";
}
# メソッドの定義
sub eaten{
$this = shift ;
my ($nums) = @_;
if($this->{Quantity}<$nums){
print "You demand $nums $this->{Name}"."s,
but there are only $this->{Quantity} $this->{Name}s. \n\n";
}else{
$this->{Quantity}-=$nums;
my $costs = $nums * $this->{Value};
print "You've got $nums $this->{Name}s. They cost $costs.\n\n" ;
}
}
# アクセスメソッドの定義
sub howmany{
my $this = shift;
print "There are $this->{Quantity} $this->{Name}"."s.\n\n";
}
# main のパッケージ名を設定
package main;
my $apple = new Fruit "Apple", 100, 30;
$apple->eaten(3);
$apple->howmany;
$apple->eaten(10);
my $banana = new Fruit "Banana", 80, 20;
$banana->eaten(10);
$banana->howmany;
$banana->eaten(20);