Perl OOP
1. 模块/类(包)创建一个名为Apple.pm的包文件(扩展名pm是包的缺省扩展名,意为Perl Module)。 2. new方法new()方法是创建对象时必须被调用的,它是对象的构造函数。 sub new {
my $class = shift;
my $this = {};
bless $this,$class;
return $this;
}
3. bless方法构造函数是类的子程序,它返回与类名相关的一个引用。 4. 类方法有两种方法:静态方法(如:构造函数)和虚方法。 5. 继承@ISA数组含有类(包)名,@INC数组含有文件路径。 类中调用的所有方法必须属于同一个类或@ISA数组定义的基类。 use Fruit;
our @ISA = qw(Fruit);
6. OOP SampleSuper Class: Fruit.pm #!/usr/bin/perl -w
use strict;
use English;
use warnings;
package Fruit;
sub prompt {
print "nFruit is good for healthn";
}
1;
Sub Class: Apple.pm #!/usr/bin/perl -w
use strict;
use English;
use warnings;
package Apple;
use Fruit;
our @ISA = qw(Fruit);
sub new {
my $class = shift;
my %parm = @_;
my $this = {};
$this -> {'name'} = $parm{'name'};
$this -> {'weight'} = $parm{'weight'};
bless $this,$class;
$this -> init();
return $this;
}
sub init {
my $reference = shift;
my $class = ref $reference;
print "class: $classn";
while (my ($key,$value) = each (%$reference))
{
print "$key = $valuen";
}
}
sub order {
my $class = ref shift;
my $customer = shift;
my $address = shift;
my $count = shift;
print "n$customer order $count $class to $addressn";
}
1;
Main Class: Purchase.pl #!/usr/bin/perl -w
use strict;
use English;
use warnings;
use Apple;
my $apple = new Apple('name' => 'Red Fuji','weight' => 300);
$apple -> prompt();
$apple -> order('Zhou Shengshuai','ChengDu',99);
Output: class: Apple
weight = 300
name = Red Fuji
Fruit is good for health
Zhou Shengshuai order 99 Apple to ChengDu
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |