码迷,mamicode.com
首页 > 其他好文 > 详细

Perl OOP

时间:2015-07-29 23:00:29      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:perl   oop   

1. 模块/类(包)

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

2. new方法

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

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

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

3. bless方法

构造函数是类的子程序,它返回与类名相关的一个引用。
bless()函数将类名与引用相关联。
其语法为:bless reference [,class]
reference: 对象的引用
class: 是可选项,指定对象获取方法的包名,缺省值为当前包名。

4. 类方法

有两种方法:静态方法(如:构造函数)和虚方法。
静态方法第一个参数为类名,虚方法第一个参数为对象的引用。
虚方法通常首先把第一个参数shift到变量self或this中,然后将该值作普通的引用使用。
静态方法直接使用类名来调用,虚方法通过该对象的引用来调用。

5. 继承

@ISA数组含有类(包)名,@INC数组含有文件路径。
当一个方法在当前包中未找到时,就到@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

版权声明:本文为博主原创文章,未经博主允许不得转载。

Perl OOP

标签:perl   oop   

原文地址:http://blog.csdn.net/three_man/article/details/47135915

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!