Perl OOP

1. 模块/类(包)

建立一个名为Apple.pm的包文件(扩展名pm是包的缺省扩展名。意为Perl Module)。
一个模块就是一个类(包)。php

2. new方法

new()方法是建立对象时必须被调用的,它是对象的构造函数。数组

sub new {
    my $class = shift;
    my $this = {};
    bless $this, $class;
    return $this;
}

this={}/ this。
bless()函数将类名与引用相关联。从new()函数返回后。$this引用被销毁。markdown

3. bless方法

构造函数是类的子程序,它返回与类名相关的一个引用。
bless()函数将类名与引用相关联。app


其语法为:bless reference [,class]
reference: 对象的引用
class: 是可选项。指定对象获取方法的包名,缺省值为当前包名。less

4. 类方法

有两种方法:静态方法(如:构造函数)和虚方法。函数


静态方法第一个參数为类名。虚方法第一个參数为对象的引用。oop


虚方法一般首先把第一个參数shift到变量self或this中,而后将该值做普通的引用使用。post


静态方法直接使用类名来调用。虚方法经过该对象的引用来调用。ui

5. 继承

@ISA数组含有类(包)名,@INC数组含有文件路径。this


当一个方法在当前包中未找到时。就到@ISA中去寻找。
@ISA中还含有当前类继承的基类。

类中调用的所有方法必须属于同一个类或@ISA数组定义的基类。
@ISA中的每个元素都是一个其余类(包)的名字。
当类找不到方法时。它会从 @ISA 数组中依次寻找(深度优先)。
类经过訪问@ISA来知道哪些类是它的基类。
e.g.

use Fruit;
our @ISA = qw(Fruit);

6. OOP Sample

Super Class: Fruit.pm

#!/usr/bin/perl -w

use strict;
use English;
use warnings;

package Fruit;

sub prompt {
    print "\nFruit is good for health\n";
}

1;

Sub Class: Apple.pm
Note: Sub class Apple.pm extends super class Fruit.pm via putting Fruit into array @ISA in 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: $class\n";

    while (my ($key, $value) = each (%$reference))
    {
        print "$key = $value\n";
    }
}

sub order {
    my $class = ref shift;
    my $customer = shift;
    my $address = shift;
    my $count = shift;

    print "\n$customer order $count $class to $address\n";
}

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
相关文章
相关标签/搜索